代码之家  ›  专栏  ›  技术社区  ›  John Meagher

正则表达式来匹配非特定子字符串的内容

  •  16
  • John Meagher  · 技术社区  · 16 年前

    例子:

    // Updated to be correct, thanks @Apocalisp
    ^foo.*(?<!bar)$
    

    应该匹配任何以“foo”开头而不以“bar”结尾的内容。我知道[^…]语法,但我找不到任何可以代替单个字符的字符串。

    我特别想为Java的regex做这件事,但我以前遇到过,所以其他regex引擎的答案也很好。

    感谢@Kibbee验证了这在C#中同样有效。

    4 回复  |  直到 15 年前
        1
  •  9
  •   Apocalisp    16 年前

    我想在这种情况下你需要 ,例如:

    foo.*(?<!bar)
    
        2
  •  1
  •   John Meagher    16 年前

    import java.util.regex.Pattern;
    public class Test {
      public static void main(String[] args) {
        Pattern p = Pattern.compile("^foo.*(?<!bar)$");
        System.out.println(p.matcher("foobar").matches());
        System.out.println(p.matcher("fooBLAHbar").matches());
        System.out.println(p.matcher("1foo").matches());
        System.out.println(p.matcher("fooBLAH-ar").matches());
        System.out.println(p.matcher("foo").matches());
        System.out.println(p.matcher("foobaz").matches());
      }
    }
    

    这将输出正确的答案:

    false
    false
    false
    true
    true
    true
    
        3
  •  1
  •   Sam Hasler zpesk    16 年前

    我不熟悉Java正则表达式,但对 Pattern Class

    foo.*(?!bar) // not correct
    

    :Apocalisp是对的,你想要负面的回顾。(您正在检查。*匹配项是否以bar结尾)

        4
  •  0
  •   aku    16 年前

    "^first_string(?!.?second_string)\\z"
    
    • ^-确保字符串以 第一组字符串
    • \z-确保字符串以第二个_字符串结尾