Question

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

Was it helpful?

Solution

Assuming your regex engine supports (negative) lookbehind:

/(?<!-)-myString/

Perl does, Javascript doesn't, for example.

OTHER TIPS

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
/^[^-]*-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

based on the last edit, I guess the following expression would work better

\b\-\w+

[^-]{0,1}-[^\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)
)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top