-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,302
  • 2
  • 24
  • 38
user1638055
  • 482
  • 2
  • 8
  • 24

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,805
  • 3
  • 43
  • 67
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,012
  • 1
  • 9
  • 29
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,302
  • 2
  • 24
  • 38
swang
  • 219
  • 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,550
  • 1
  • 13
  • 22