簡體   English   中英

Java-正則表達式匹配中的意外結果

[英]java - Unexpected result in Regex match

我正在嘗試檢查每一行是否等於“測試”。 當我嘗試運行以下代碼時,我希望結果為true,因為每一行都是“測試”。 然而,結果是錯誤的。

// Expected outcome:
// "test\ntest\ntest" - should match
// "test\nfoo\ntest" - should not match
// "test\ntesttest\ntest" - should not match

Pattern pattern = Pattern.compile("^test$", Pattern.MULTILINE);
Matcher matcher = pattern.matcher("test\ntest");

System.out.println(matcher.matches()); // result is false

我在這里想念什么? 為什么結果是假的?

由於您正在使用Pattern.MULTILINE ,因此它與整個字符串test\\ntest匹配。 但是在您的正則表達式中,您指定該字符串應僅由test的單個實例組成,因為它由開始和結束錨點包圍。

使用Pattern.compile("^test$", Pattern.MULTILINE) ,您只要求正則表達式引擎匹配一行等於test 使用Matcher#matches() ,您告訴正則表達式引擎匹配完整字符串。 由於您的字符串不等於test ,因此結果為false

要驗證包含全部等於test行的字符串,可以使用

Pattern.compile("^test(?:\\Rtest)*$")

在較早的Java版本中,您將需要用\\n\\r?\\n替換\\R (任何換行符)。

觀看在線演示

Pattern pattern = Pattern.compile("^test(?:\\Rtest)*$");
Matcher matcher = pattern.matcher("test\ntest");
System.out.println(matcher.matches()); // => true

Pattern.MULTILINE允許您的正則表達式在行分隔符之前和之后匹配^$ ,這不是默認行為。 默認設置是僅在輸入的開頭和結尾匹配。

但是,如果使用matchs(),它將嘗試將正則表達式與整個輸入文本進行匹配,從而產生false,因為輸入不僅等於"test"

盡管matchs()不起作用,但是您可以使用find()查找與正則表達式匹配的輸入的子序列。 因為^$\\n之前和之后匹配,所以您的模式會找到兩個子序列。

但這只是我的兩分錢。

Pattern pattern = Pattern.compile("^test$", Pattern.MULTILINE);
Matcher matcher = pattern.matcher("test\ntest");

System.out.println(matcher.matches()); // prints "false", the whole input doesn't match a single "test"

System.out.println(matcher.find());    // prints "true"
System.out.println(matcher.group());   // prints "test"

System.out.println(matcher.find());    // prints "true"
System.out.println(matcher.group());   // prints "test"

System.out.println(matcher.find());    // prints "false"

暫無
暫無

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

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