Java正则表达式问号
当尝试将Java正则表达式问号,java,regex,Java,Regex,当尝试将“??M?E???”与模式“^([\\?]+)M([\\?]+)E([\\?]+)$”匹配时,我得到“不匹配”,尽管它对“?M?E???”很好 我的代码片段是 Pattern p = Pattern.compile("^([?]+)[M]{1}([?]+)[E]{1}([?]+)$"); Matcher m = p.matcher(input); if ( !m.find() ) { System.out.p
“??M?E???”
与模式“^([\\?]+)M([\\?]+)E([\\?]+)$”
匹配时,我得到“不匹配”,尽管它对“?M?E???”很好
我的代码片段是
Pattern p = Pattern.compile("^([?]+)[M]{1}([?]+)[E]{1}([?]+)$");
Matcher m = p.matcher(input);
if ( !m.find() ) {
System.out.println("No Match");
continue ;
}
x = m.group(1).length();
y = m.group(2).length();
z = m.group(3).length();
你应该很好,你的正则表达式很好。请注意,您不需要在字符类中转义?
,只需执行以下操作:
^([?]+)M([?]+)E([?]+)$
或者,逃离它,但把它带出课堂*:
*注意,在Java中,\
表示为\\
编辑问题并发布实际代码后,看起来您有不同的正则表达式(下次请不要这样做),您应该使用匹配项
,而不是查找
。您的问题一定是因为input
的内容,它根本不会使find
返回true
,请注意find
尝试查找与正则表达式匹配的子字符串中的下一个匹配项。您的代码看起来像什么?这很好:
Pattern pattern = Pattern.compile("^([\\?]+)M([\\?]+)E([\\?]+)$");
System.out.println(pattern.matcher("??M?E???").matches());
System.out.println(pattern.matcher("?M?E??").matches());
输出:
true
true
我尝试了你编辑后发布的代码,效果很好。为?ME???
生成2,1,3
,为?ME???
生成1,1,2
。你一定是做错了什么,在你没有发布的代码中,或者你的输入实际上和你说的不一样。
true
true