簡體   English   中英

Java RegEx負面的lookbehind

[英]Java RegEx negative lookbehind

我有以下Java代碼:

Pattern pat = Pattern.compile("(?<!function )\\w+");
Matcher mat = pat.matcher("function example");
System.out.println(mat.find());

為什么mat.find()返回true? 我使用了負面的lookbehind, example前面是function 不應該被丟棄嗎?

看看它匹配的內容:

public static void main(String[] args) throws Exception {
    Pattern pat = Pattern.compile("(?<!function )\\w+");
    Matcher mat = pat.matcher("function example");
    while (mat.find()) {
        System.out.println(mat.group());
    }
}

輸出:

function
xample

所以首先找到function ,它不是“ function ”。 然后它找到xample ,其前面是function e ,因此不是“ function ”。

大概你希望模式匹配整個文本,而不只是文本中找到匹配。

您可以使用Matcher.matches()執行此操作,也可以更改模式以添加開始和結束錨點:

^(?<!function )\\w+$

我更喜歡第二種方法,因為它意味着模式本身定義了它的匹配區域,而不是由其用法定義的區域。 然而,這只是一個偏好問題。

你的字符串有“function”字樣與\\ w +匹配,並且前面沒有“function”。

請注意兩件事:

  • 您正在使用find() ,它也會為子字符串匹配返回true

  • 由於上述原因,“功能”匹配,因為它沒有“功能”。
    整個字符串永遠不會匹配,因為你的正則表達式不包含空格。

使用Mathcher#matches()^$ anchors以及負向前瞻:

Pattern pat = Pattern.compile("^(?!function)[\\w\\s]+$"); // added \s for whitespaces
Matcher mat = pat.matcher("function example");

System.out.println(mat.find()); // false

暫無
暫無

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

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