[英]Regex to match only letters and numbers
您可以提供此代碼幫助嗎?
看起來很簡單,但總是失敗。
@Test
public void normalizeString(){
StringBuilder ret = new StringBuilder();
//Matcher matches = Pattern.compile( "([A-Z0-9])" ).matcher("P-12345678-P");
Matcher matches = Pattern.compile( "([\\w])" ).matcher("P-12345678-P");
for (int i = 1; i < matches.groupCount(); i++)
ret.append(matches.group(i));
assertEquals("P12345678P", ret.toString());
}
構造Matcher
器不會自動執行任何匹配。 部分原因是Matcher
支持兩種不同的匹配行為,區別在於匹配是否隱式地錨定到Matcher
區域的開頭。 看來您可以達到所需的結果,如下所示:
@Test
public void normalizeString(){
StringBuilder ret = new StringBuilder();
Matcher matches = Pattern.compile( "[A-Z0-9]+" ).matcher("P-12345678-P");
while (matches.find()) {
ret.append(matches.group());
}
assertEquals("P12345678P", ret.toString());
}
特別要注意Matcher.find()
的調用,這是您的版本中的一個關鍵遺漏。 同樣,無效的Matcher.group()
返回與最后一個find()
匹配的子字符串。
此外,盡管您對Matcher.groupCount()
使用並不完全錯誤,但它的確使我懷疑您對它的用途有錯誤的認識。 特別是,在您的代碼中,它將始終返回1
-它查詢模式 ,而不是與其匹配。
首先,您不需要添加任何組,因為整個匹配始終可以由組0訪問,因此
(regex)
和group(1)
您可以使用
regex
和group(0)
接下來的事情是\\\\w
已經是字符類,因此您不需要用另一個[
]
包圍它,因為它類似於[[az]]
,與[az]
相同。
現在在你的
for (int i = 1; i < matches.groupCount(); i++)
ret.append(matches.group(i));
您將遍歷所有組1
,但你會排除最后一組,因為它們是從索引1
所以n
所以i<n
將不包括n
。 您將需要使用i <= matches.groupCount()
代替。
同樣,您似乎也感到困惑。 此循環不會在輸入中找到所有正則表達式匹配項。 找到 regex的匹配后 ,使用這樣的循環遍歷使用過的regex中的組。
因此,如果正則表達式是(\\w(\\w))c
而您的匹配項是abc
那么
for (int i = 1; i < matches.groupCount(); i++)
System.out.println(matches.group(i));
會打印
ab
b
因為
c
之前包含兩個字符(\\w(\\w))
但是要打印它們,您實際上首先需要讓正則表達式引擎遍歷您的輸入和find()
匹配項,或者檢查整個輸入是否matches()
regex,否則您將收到IllegalStateException
因為正則表達式引擎無法從您想要的匹配項中得知獲取您的組(輸入中可能有很多正則表達式匹配項)。
所以您可能想要使用的是
StringBuilder ret = new StringBuilder();
Matcher matches = Pattern.compile( "[A-Z0-9]" ).matcher("P-12345678-P");
while (matches.find()){//find next match
ret.append(matches.group(0));
}
assertEquals("P12345678P", ret.toString());
其他方法(可能是更簡單的解決方案)實際上是從輸入中刪除所有不需要的字符。 因此,您可以只使用replaceAll
和否定的字符類[^...]
String input = "P-12345678-P";
String result = input.replaceAll("[^A-Z0-9]+", "");
它將產生一個新字符串,其中所有非A-Z0-9
字符都將被刪除(替換為""
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.