2

我如何用正则表达式做到这一点?

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

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

myString 当然是任何东西。

有可能吗?

编辑:

自从我发布了一个问题以来,这里有更多关于我到目前为止所获得的信息:

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

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

理想情况下,我希望它只返回-string1匹配项

4

6 回答 6

11

假设您的正则表达式引擎支持(负)lookbehind:

/(?<!-)-myString/

例如,Perl 会,Javascript 不会。

于 2009-02-09T16:36:37.103 回答
0
/^[^-]*-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
于 2009-02-09T16:34:22.650 回答
0

你想匹配一个以单个破折号开头的字符串,而不是包含多个破折号的字符串?

^-[^-]

解释:

^ Matches start of string
- Matches a dash
[^-] Matches anything but a dash
于 2009-02-09T16:35:14.377 回答
0

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

于 2009-02-09T16:36:19.680 回答
0

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

\b\-\w+
于 2009-02-09T17:01:14.767 回答
0

不使用任何后视,使用:

(?:^|(?:[\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)
)
于 2009-02-09T18:40:58.633 回答