2014-01-17 764 views
2

我需要編寫只允許數字的正則表達式,如& | 。 ()和空格。Java正則表達式 - 只允許某些字符和數字

import java.util.*; 
import java.lang.*; 
import java.io.*; 

/* Name of the class has to be "Main" only if the class is public. */ 
class Ideone 
{ 
    public static void main (String[] args) throws java.lang.Exception 
    { 

     List<String> input = new ArrayList<String>(); 
     input.add("(0.4545 && 0.567) || 456"); // should PASS 
     input.add("9876-5-4321"); 
     input.add("987-65-4321 (attack)"); 
     input.add("(0.4545 && 0.567) || 456 && (me)"); 
     input.add("0.456 && 0.567"); // should PASS 
     for (String ssn : input) { 
      boolean f = ssn.matches("^[\\d\\s()&|.]$"); 
      if (f) { 
       System.out.println("Found good SSN: " + ssn); 
      }else { 
       System.out.println("Nope: " + ssn); 
      } 
     } 
    } 
} 

以上都沒有通過,爲什麼?

+0

搜索在線正則表達式的棋子之一,並確認正則表達式做什麼你認爲它... – John3136

回答

5

你忘了在字符類後添加+。沒有它,你的正則表達式將只接受來自角色類的字符的單字符串。與

boolean f = ssn.matches("^[\\d\\s()&|.]+$"); 
+0

WOOW,謝謝。我忘了添加+,完美的作品。 – antohoho

+0

@antohoho歡迎您:) – Pshemo

2

嘗試,因爲你的正則表達式只接受單一輸入(無論是數字或字符或指定的符號)

使用^[\\d\\s()&|.]*$爲獲得多次

「+ 1或更多的」

? 0或一個

「* 0個或多個」

相關問題