-1

I have a string, it can either be "word" or "word (something)". How can I only match "word", but not "word (something)"?

Nick
  • 4,206
  • 2
  • 22
  • 36
user1638055
  • 442
  • 2
  • 8
  • 22

4 Answers4

7

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
Phillip Schmidt
  • 8,675
  • 3
  • 42
  • 66
1

you can use ^word$.

here ^ sign indicates start of string and $ indicates end of string

so it will match to "word" only ..

Patriks
  • 1,006
  • 1
  • 9
  • 28
0

From the python manual:

(?!...)

This is a negative lookahead assertion. Matches characters if ... doesn’t match next character set.

For example, Isaac (?!Asimov) will match 'Isaac ' only if it’s not followed by 'Asimov'.

Nick
  • 4,206
  • 2
  • 22
  • 36
swang
  • 221
  • 1
  • 3
0

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(?! \([^)]*\))
skunkfrukt
  • 1,492
  • 1
  • 13
  • 21