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

一个我无法解决的正则表达式问题(负面向后看)

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

    如何使用正则表达式来实现这一点?

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

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

    myString当然是任何东西。

    这有可能吗?

    编辑:

    自从我发布了一个问题以来,我得到了更多的信息:

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

    此正则表达式返回3个匹配项: -string1 , - -string2

    理想情况下,我只想把它还给我 -串1 比赛

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

    假设你的正则表达式引擎支持(否定)后视镜:

    /(?<!-)-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)
    )
    
    推荐文章