我想让regx匹配2个或1个字符的任何单词的示例(是,或,如果是,)
我试过了:-
int scount = 0;
String txt = "hello everyone this is just test aa ";
Pattern p2 = Pattern.compile("\\w{1,2}");
Matcher m2 = p2.matcher(txt);
while (m2.find()) {
scount++;
}
但匹配错误。
您可能要使用单词边界锚点:
Pattern p2 = Pattern.compile("\\b\\w{1,2}\\b");
这些锚点在字母数字“单词”的开头/结尾匹配,也就是说,\w
如果\w
字符之前没有字符,则在字符之前的位置;如果字符之后没有字符,\w
则在\w
字符之后的位置匹配。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句