簡體   English   中英

為什么我的負面觀察不適用於Java?

[英]Why does my negative lookbehind not work in Java?

我試圖使用負向lookbehind來對字符串進行一些匹配,這些字符串將從我們所討論的另一個系統發送到系統中。 我搜索過類似的問題,但我無法根據之前發布的任何問題解決此問題。

這按預期工作

Pattern pattern = Pattern.compile ("^(?<!SyCs-)([A-Za-z\\s\\d]+)$");
String s = "SyCs-a";

Assert.assertEquals (false, pattern.matcher (s).matches ());

這是問題:對於當前正則表達式,以下也返回false,這是有道理的,因為' - '(破折號)不是允許值的一部分([A-Za-z \\ s \\ d] +)

s = "TyCs-a";

Assert.assertEquals (false, pattern.matcher (s).matches ());

但是,我需要返回true,但是當我將破折號添加到允許值時,第一個String也返回true。

沒有沖刺

Pattern pattern = Pattern.compile ("^(?<!SyCs-)([A-Za-z\\s\\d]+)$");
String s = "SyCs-a";

Assert.assertEquals (false, pattern.matcher (s).matches ());

s = "TyCs-a";

Assert.assertEquals (false, pattern.matcher (s).matches ());

用破折號

Pattern pattern = Pattern.compile ("^(?<!SyCs-)([A-Za-z\\s\\d-]+)$");
String s = "SyCs-a";

Assert.assertEquals (true, pattern.matcher (s).matches ());

s = "TyCs-a";

Assert.assertEquals (true, pattern.matcher (s).matches ());

我試過讓+不貪婪+? 但這根本不會改變結果。

有什么建議?

這是我用來驗證正則表達式的整套測試

@Test
public void testNegativeLookBehind () {
    Pattern pattern = Pattern.compile ("^(?<!SyCs-)([A-Za-z\\s\\d]+)$");
    String s = "SyCs-a";

    Assert.assertEquals (false, pattern.matcher (s).matches ());

    s = "SyCs-b";

    Assert.assertEquals (false, pattern.matcher (s).matches ());

    s = "SyCs-ab";

    Assert.assertEquals (false, pattern.matcher (s).matches ());

    s = "SyCs-ab1";

    Assert.assertEquals (false, pattern.matcher (s).matches ());

    s = "SyCs-abZ";

    Assert.assertEquals (false, pattern.matcher (s).matches ());

    s = "SyCs- abZ";

    Assert.assertEquals (false, pattern.matcher (s).matches ());

    s = "SyCs ab1";

    Assert.assertEquals (true, pattern.matcher (s).matches ());

    /*s = "TyCs-a";

    Assert.assertEquals (true, pattern.matcher (s).matches ());

    s = "SyCr-a";

    Assert.assertEquals (true, pattern.matcher (s).matches ());
    */
    s = "ab";

    Assert.assertEquals (true, pattern.matcher (s).matches ());

    s = "sab";

    Assert.assertEquals (true, pattern.matcher (s).matches ());

    s = "Csab";

    Assert.assertEquals (true, pattern.matcher (s).matches ());

    s = "yCsab";

    Assert.assertEquals (true, pattern.matcher (s).matches ());

    s = "SyCsab";

    Assert.assertEquals (true, pattern.matcher (s).matches ());
}

(?<!SyCs-)是負面的后視,如果有CyCs-當前位置的左側,則CyCs-匹配失敗。 由於當前位置是字符串( ^ )的開頭,因此lookbehind 總是返回true並且無用。

你需要在這里使用一個前瞻,而不是一個lookbehind:

String pat = "^(?!SyCs-)[A-Za-z\\s\\d-]+$";
               ^^^^^^^^^

請參閱正則表達式演示

^(?!SyCs-)將檢查字符串是否以SyCs- - 如果是,則匹配將失敗。

請注意,如果將模式與.matches()方法一起使用,則可以省略模式中的^$ anchors,因為該方法需要完整的字符串匹配。

暫無
暫無

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

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