Reputation: 15677
how do i do this with regex?
i want to match this string: -myString
but i don't want to match the -myString
in this string: --myString
myString is of course anything.
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
ideally i'd like it to return me only the -string1
match
Upvotes: 2
Views: 2586
Reputation: 1190
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)
)
Upvotes: 0
Reputation: 561
based on the last edit, I guess the following expression would work better
\b\-\w+
Upvotes: 0
Reputation: 425271
/^[^-]*-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
Upvotes: 0
Reputation: 7767
Assuming your regex engine supports (negative) lookbehind:
/(?<!-)-myString/
Perl does, Javascript doesn't, for example.
Upvotes: 11
Reputation: 75704
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
Upvotes: 0