[英]A regex problem I can't figure out (negative lookbehind)
how do i do this with regex? 我如何用正则表达式做到这一点?
i want to match this string: -myString
我想匹配这个字符串:
-myString
but i don't want to match the -myString
in this string: --myString
但我不想匹配此字符串中的
-myString
: - --myString
myString is of course anything. myString当然是什么。
is it even possible? 它甚至可能吗?
EDIT: 编辑:
here's a little more info with what i got so far since i've posted a question: 这里有一些关于我到目前为止所得到的信息,因为我发布了一个问题:
string to match:
some random stuff here -string1, --string2, other stuff here
regex:
(-)([\w])*
This regex returns me 3 matches: -string1
, -
and -string2
这个正则表达式返回3个匹配:
-string1
, -
和-string2
ideally i'd like it to return me only the -string1
match 理想情况下,我希望它只返回
-string1
匹配
Assuming your regex engine supports (negative) lookbehind: 假设你的正则表达式引擎支持(负面)lookbehind:
/(?<!-)-myString/
Perl does, Javascript doesn't, for example. Perl确实如此,Javascript没有。
/^[^-]*-myString/
Testing: 测试:
[~]$ 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
You want to match a string that starts with a single dash, but not one that has multiple dashes? 您希望匹配以单个破折号开头的字符串,但不匹配具有多个破折号的字符串?
^-[^-]
Explanation: 说明:
^ Matches start of string
- Matches a dash
[^-] Matches anything but a dash
[^ - ] {0,1} - [^ \\ W - ] +
根据上次编辑,我猜以下表达式会更好
\b\-\w+
Without using any look-behinds, use: 不使用任何后视镜,请使用:
(?:^|(?:[\s,]))(?:\-)([^-][a-zA-Z_0-9]+)
Broken out: 爆发:
(
?:^|(?:[\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)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.