簡體   English   中英

非常簡單的Java正則表達式沒有給出預期的結果

[英]Very simple Java regex not giving expected result

今天是我第一天通過Thinking in Java 4th Edition中的Strings章節學習正則表達式(在此之前沒有背景)。 我正在拉我的頭發,為什么正則表達式不匹配輸入字符串的任何區域。 我在regex101中對此進行了測試,得到了我期望的結果,但是在Java中(你無法在regex101網站上測試),結果是不同的。
編輯:在本章中進行練習10

正則表達式: nw\\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
*/

使用boolean matchFound = m.find(); 而不是boolean matchFound = m.lookingAt();

來自Javadocs

lookingAt()嘗試lookingAt()區域開頭開始的輸入序列與模式匹配。

使用m.find()而不是m.lookingAt()

您可以打印m.group()獲得的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是

public boolean lookingAt()

嘗試將輸入序列(從區域的開頭開始)與模式匹配。 與匹配方法一樣,此方法始終從區域的開頭開始; 與該方法不同,它不需要匹配整個區域。

如果匹配成功,則可以通過start,end和group方法獲得更多信息。

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

這意味着,此方法需要在輸入String的最開頭處使用正則表達式匹配。

此方法不經常使用,效果就像您將正則表達式修改為"^nw\\\\s+h(a|i)s" ,並使用find()方法。 它還給出了正則表達式在輸入String的最開頭匹配的限制。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM