今天是我第一天學習正則表達式(在此之前從字面上看沒有背景),通過書中Thinking in Java 4th Edition一章中的Strings一章。我拉我的頭髮爲什麼正則表達式不匹配輸入字符串的任何區域。我已經在regex101中測試過了,我得到了我期望的結果,但是在Java中(你不能在regex101網站上測試),結果是不同的。
編輯:一章中做運動10非常簡單的Java正則表達式沒有給出預期的結果
正則表達式:n.w\s+h(a|i)s
輸入字符串:Java now has regular expressions
預期成果:在輸入字符串
實際結果的區域"now has"
找到匹配:沒有找到匹配
我的相關代碼:
import java.util.regex.*;
public class Foo {
public static void main(String[] args) {
// NOTE: I've also tested passing the regex as an arg from the command line
// as "n.w\s+h(a|i)s"
String regex = "n.w\\s+h(a|i)s";
String input = "Java now has regular expressions";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
// Starting at the beginning of the input string, look for a match in ANY
// region of the input string
boolean matchFound = m.lookingAt();
System.out.println("Match was found: " + matchFound);
}
}
/* OUTPUT
-> Match was found: false
*/
這是我一直在尋找的詳細答案,感謝您以初學者友好的方式解釋文檔。我最好不使用lookAt(),而是改變我的正則表達式來使用find()? – Wrap2Win
你最好檢查http://stackoverflow.com/questions/30008397/whats-the-difference-between-matcher-lookingat-and-find以獲得更詳細的解釋 – Gearon