2013-04-11 27 views
1

我的源驗證合規性的(正則表達式)

Matcher matcher = Pattern.compile("[0-9]").matcher("35423523");

matcher.matches() - 現在是假

,但我需要matcher.matches() - true - 因爲該字符串是所有數字

或例如

Pattern.compile("[0-9A-Za-z]").matcher("35dwedwfeASADdfd423523"); - 必須爲真

Pattern.compile("[0-9]").matcher("354ccwq23523"); - 一定是假的 或Pattern.compile("[0-9a-z]").matcher("354ccwq23523"); - 必須是真實的

如何做到這一點?

回答

5

你的正則表達式說該字符串只能是一個字符寬,如果你想要更多,你應該使用repetition。然後它看起來像這樣:[0-9]+[0-9A-Za-z]+

+0

我不明白爲什麼這會是必要的,但對錨的解釋可以發現[這裏](HTTP:/ /www.regular-expressions.info/anchors.html) – errieman 2013-04-11 08:36:20

+0

對不起我的壞。混淆'.match'與'.find()'。 – npinti 2013-04-11 08:37:24

2

matches()方法檢查the entire region against the pattern。這意味着你的模式需要匹配整個字符串:

Matcher matcher = Pattern.compile("[0-9]+").matcher("35423523"); 

Pattern.compile("[0-9A-Za-z]+").matcher("35dwedwfeASADdfd423523"); 

從的javadoc:

返回true:當且僅當整個區域序列匹配此匹配器的模式

2
Pattern.compile("[0-9]+").matcher("35423523"); 

TRUE

Pattern.compile("[0-9A-Za-z]+").matcher("35dwedwfeASADdfd423523"); 

TRUE

Pattern.compile("[0-9]+").matcher("354ccwq23523"); 

FALSE

Pattern.compile("[0-9a-z]+").matcher("354ccwq23523"); 

TRUE

如果你想匹配,你可以使用[0-9]{1, 4}(下限 - >上限)特定長度