I have a string, it can either be "word" or "word (something)". How can I only match "word", but not "word (something)"?
-
Does it have to be in parenthesis? – h2ooooooo Sep 25 '12 at 13:54
4 Answers
Depending on the regex flavor, you can probably use a negative lookahead. Like this:
word(?! \(something\))
Just checks to make sure there isn't a space and the word something after the matched word.
Oh, and if you have JUST the word "word" in the string, you could do:
^word$
which makes sure that word
is the start (^)
and the end ($)
of the string.
But if you had JUST the word "word" in the string, you could have just done
wordString == "word"; // or wordVariable in place of "word", or whatever

- 8,805
- 3
- 43
- 67
-
3
-
@m.buettner was doing it as you made the comment :) lol just forgot to put it in there – Phillip Schmidt Sep 25 '12 at 13:57
you can use ^word$
.
here ^ sign indicates start of string and $ indicates end of string
so it will match to "word" only ..

- 1,012
- 1
- 9
- 29
Judging by the fact that you phrased the string you do not want to match differently in the title and the actual question, I am assuming that you do not mean the literal strings "whatever" and "something".
Provided that you are using a regex flavour that supports negative lookahead, this should work:
word(?! \([^)]*\))

- 1,550
- 1
- 13
- 22