您可以提供此代码帮助吗?
看起来很简单,但总是失败。
@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());
}
构造aMatcher
不会自动执行任何匹配。这部分是因为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()
返回与last匹配的子字符串find()
。
此外,尽管您对的使用Matcher.groupCount()
并不完全错误,但确实使我怀疑您对它的用途有错误的认识。特别是,在您的代码中它将始终返回1
-它查询模式,而不是与其匹配的内容。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句