2016-11-13 36 views
1

今天是我第一天學習正則表達式(在此之前從字面上看沒有背景),通過書中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 
*/ 

回答

1

使用m.find()代替m.lookingAt()

可以打印你所得到的由m.group()

請在下面校驗碼。

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.find(); 
     System.out.println("Match was found: " + matchFound); 
     System.out.println("Matched string is: " + m.group()); 
    } 
} 

lookingAt的的JavaDoc()是

公共布爾lookingAt()

嘗試匹配輸入序列,開始於 區域的開始,針對所述圖案。像匹配方法一樣,這個方法 總是從該區域的開始處開始;與該方法不同,它不需要整個區域匹配。

如果匹配成功,則可以通過 開始,結束和組方法獲取更多信息。

返回:當且僅當輸入序列的前綴匹配 此匹配器模式

這意味着,這種方法需要正則表達式在輸入字符串的最開始匹配。

這種方法不經常使用,效果就像你修改你的正則表達式爲"^n.w\\s+h(a|i)s",並使用find()方法。它還會限制正則表達式在輸入字符串的最開始處匹配。

+0

這是我一直在尋找的詳細答案,感謝您以初學者友好的方式解釋文檔。我最好不使用lookAt(),而是改變我的正則表達式來使用find()? – Wrap2Win

+0

你最好檢查http://stackoverflow.com/questions/30008397/whats-the-difference-between-matcher-lookingat-and-find以獲得更詳細的解釋 – Gearon

2

使用boolean matchFound = m.find();代替boolean matchFound = m.lookingAt();

從Javadoc中

lookingAt()嘗試匹配輸入序列,開始於區域的開始,針對所述圖案。

+0

完美地工作,如果你能解釋爲什麼lookingAt()不按我想的方式工作,我會接受這個答案。 – Wrap2Win

+0

如果你的輸入字符串是''現在有正則表達式'''那麼lookingAt將返回true。 – iNan

+0

@RNGesus [文檔](https://docs.oracle。com/javase/8/docs/api/java/util/regex/Matcher.html)解釋了Matcher方法之間的區別。 – VGR

相關問題