這是示例代碼Java的正則表達式 - Pattern.match無法對付懶惰的比賽
String m_testPattern = "AB.*?";
String m_testMatcherString = "ABCDCDCDCD";
final Pattern pattern = Pattern.compile(m_testPattern);
final Matcher matcher = pattern.matcher(m_testMatcherString);
if (matcher.matches()) {
// This means the regex matches
System.out.println("Successful comparison");
} else {
// match failed
System.out.println("Comparison failed !!!");
}
理想的匹配操作應導致失敗,給我輸出爲「比較失敗!!!」
但是這個代碼片斷讓我
我在網上查了正則表達式工具,相同的輸入和結果是不同的
我沒有在這個網站上的審判「比較成功」作爲輸出http://regexr.com/v1/
在這裏,當我把AB。*?在正則表達式和ABCDCDCDCD中作爲要比較的字符串,然後在AB處停止搜索。 這意味着執行的比較是懶惰的比較而不是貪婪的比較
任何人都可以請解釋爲什麼相同的用例在Java Pattern.match函數的情況下失敗嗎?
我的測試情況是一樣的東西
1.正則表達式AB \ WCD應與ABZCD加上AB2CD
2.失敗AB \ w {2} CD將匹配ABZZCD
3. AB \ d {1, 3} CD應與AB555CD或AB6CD相匹配或AB77CD在ABCD或AB9999CD等處出現故障
4. AB。*應與AB匹配(後面跟着任何內容)
5. AB。*?如果像ABCDCDCD輸入,給出了比較提前
All the 4 steps is passed successfully while using matcher.matches() function <br/>
Only the fifth one gives a wrong answer. (5th scenario also gives a success message eventhough it should fail)
感謝
'matches()'聲明**整個輸入**匹配正則表達式(正則表達式被隱式錨定),這是因爲'*'允許'.'重複沒有限制。正則表達式測試人員通常只做一些與Matcher.find()不相同的東西,因爲'。*?'表現出懶惰,並且匹配一個空字符串。 – nhahtdh
感謝您的快速回復 如果我使用Matcher.find()方法,則此用例按預期方式工作,但其他簡單輸入(如常規AB。*)無法與ABCDCDCD – Mparame
相匹配。您尚不清楚此處要做什麼。你想驗證,還是從一些文本中提取內容? – nhahtdh