[英]Java Regex Question Mark
嘗試匹配"??M?E???"
使用模式"^([\\\\?]+)M([\\\\?]+)E([\\\\?]+)$"
,我得到“ No match”,盡管它適用於"?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([?]+)$
或者,將其轉義,但從類*中刪除:
^(\?+)M(\?+)E(\?+)$
*請注意,在Java中, \\
表示為\\\\
編輯問題並發布實際代碼后,看起來您有不同的正則表達式(請下次不要這樣做),應使用matches
而不是find
。 您的問題一定是由於input
的內容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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.