Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何仅将1或2个字符与正则表达式匹配_Java_Regex_Matcher - Fatal编程技术网

Java 如何仅将1或2个字符与正则表达式匹配

Java 如何仅将1或2个字符与正则表达式匹配,java,regex,matcher,Java,Regex,Matcher,我希望regx匹配任何2或1个字符的单词,例如is、an或,如果是a 我试过这个:- 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++; } 但匹配错误。您可能希望使用: 这些锚定符在字母数字字的开

我希望regx匹配任何2或1个字符的单词,例如is、an或,如果是a

我试过这个:-

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++;
}
但匹配错误。

您可能希望使用:

这些锚定符在字母数字字的开头/结尾匹配,即如果前面没有字符,则在字符前面的位置匹配,如果后面没有字符,则在字符后面匹配。

您可能希望使用:


这些锚定符在字母数字单词的开始/结束处匹配,也就是说,如果前面没有\w字符,则在\w字符之前的位置匹配,如果后面没有\w字符,则在\w字符之后匹配。

我认为您应该更具描述性。您当前的代码来自变量Scont。那不是什么

若你们想得到一个2个字母单词的计数,也就是不包括下划线,这个计数中的数字,我认为你们最好使用负环视法:

Pattern.compile("(?i)(?<![a-z])[a-z]{1,2}(?![a-z])");
对于hello everyone的字符串输入,这只是1个测试aa,您得到的Scont值为2 is和aa,而不是3 is,1,aa,如果您只查找1或2个连续的\w


另外,大家好,这只是测试aa,在lookarounds中,计数为1,而在lookarounds中,计数为2,aa。

我认为您应该更具描述性。您当前的代码来自变量Scont。那不是什么

若你们想得到一个2个字母单词的计数,也就是不包括下划线,这个计数中的数字,我认为你们最好使用负环视法:

Pattern.compile("(?i)(?<![a-z])[a-z]{1,2}(?![a-z])");
对于hello everyone的字符串输入,这只是1个测试aa,您得到的Scont值为2 is和aa,而不是3 is,1,aa,如果您只查找1或2个连续的\w


另外,大家好,这只是测试aa,在lookarounds中,计数为1,而在lookarounds中计数为2,aa。

什么是“无”?你应该有一些匹配。事实上,你的代码每两个或一个字母匹配一次。这就是我的输出:他,ll,o,ev,er,yo,ne,th,is,is,ju,st,te,st,aa。这是什么意思?你应该有一些匹配。事实上,你的代码每两个或一个字母匹配一次。这就是我的输出:他,ll,o,ev,er,yo,ne,th,is,is,ju,st,te,st,aa。