代码之家  ›  专栏  ›  技术社区  ›  Mladen Prajdic

一个我搞不清的正则表达式问题(否定查找)

  •  2
  • Mladen Prajdic  · 技术社区  · 16 年前

    我该如何处理regex?

    我想匹配这个字符串: -myString

    但我不想和 -字符串 在这个字符串中: --myString

    我的肌腱当然是任何东西。

    有可能吗?

    编辑:

    以下是我发布问题以来获得的更多信息:

    string to match:
    some random stuff here -string1, --string2, other stuff here
    regex:
    (-)([\w])*
    

    此regex返回3个匹配项: -string1 , - -string2

    理想情况下,我只想把 -STRIG1 比赛

    6 回复  |  直到 15 年前
        1
  •  11
  •   bart    16 年前

    假设您的regex引擎支持(否定)lookbehind:

    /(?<!-)-myString/
    

    例如,Perl可以,Javascript不能。

        2
  •  0
  •   soulmerge    16 年前

    您想匹配一个以一个破折号开始的字符串,但不是一个有多个破折号的字符串?

    ^-[^-]
    

    说明:

    ^ Matches start of string
    - Matches a dash
    [^-] Matches anything but a dash
    
        3
  •  0
  •   Quassnoi    16 年前
    /^[^-]*-myString/
    

    测试:

    [~]$ echo -myString | egrep -e '^[^-]*-myString'
    -myString
    [~]$ echo --myString | egrep -e '^[^-]*-myString'
    [~]$ echo test--myString | egrep -e '^[^-]*-myString'
    [~]$ echo test --myString | egrep -e '^[^-]*-myString'
    [~]$ echo test -myString | egrep -e '^[^-]*-myString'
    test -myString
    
        4
  •  0
  •   Mohamed Ali    16 年前

    根据上次的编辑,我想下面的表达式会更好地工作

    \b\-\w+
    
        5
  •  0
  •   Joel Coehoorn    16 年前

    [^-]0,1-[^\w-]+

        6
  •  0
  •   Neil Monroe    16 年前

    在不使用任何外观的情况下,使用:

    (?:^|(?:[\s,]))(?:\-)([^-][a-zA-Z_0-9]+)
    

    爆发:

    (
      ?:^|(?:[\s,])        # Determine if this is at the beginning of the input,
                           # or is preceded by whitespace or a comma
    )
    (
      ?:\-                 # Check for the first dash
    )
    (
      [^-][a-zA-Z_0-9]+    # Capture a string that doesn't start with a dash
                           # (the string you are looking for)
    )