2

I am trying to learn RegEx and build a regular expression that would look whether specified word is NOT in the provided string. So far I did try Regular Expression Info and RexxEgg all this tested on Regular Expression Online but I did not find the answer to my question.

I have tried conditionals and lookarounds. Let's say I want to build an expression to test against not existing word myword and pass expression when the word is NOT in the string. I used expression

(?(?!myword).*)

but RegEx passes regardless the word myword meaning both strings This is the text and This is myword the text pass the test.

Using negative lookahead and conditions is used to test that condition is true when myword does not exist. Lookahead is also zero length and therefore .* would return the whole string.

Hope someone can help :)

Celdor
  • 2,437
  • 2
  • 23
  • 44

2 Answers2

3
^(?(?!\bmyword\b).)*$

You can try this.See demo.Also use \b for matching exactly myword and not mywords

https://regex101.com/r/hI0qP0/7

vks
  • 67,027
  • 10
  • 91
  • 124
  • Yes. It's working. thanks. The difference between mine and yours is you have only one dot and start behind brackets. Why is that? – Celdor Jun 13 '15 at 22:09
  • @Celdor your regex said....check if there is `myword` then match all....this regex says....`at every point check if myword` is there or not....so the quantifier is outside and each `.` is being tested for myword....whereas in ur case it was being tested only once – vks Jun 13 '15 at 22:12
  • Yes it works, thanks. I just need to read more about RegEx and lookaround. I find it quite confusing. – Celdor Jun 13 '15 at 22:34
  • 1
    @Celdor `?!` is `negative lookahead`.So engine will look ahead to see if the match is not der.Only then it will pass.Your regex checks at the start if `myword` is not der.If that's ok it consumes the rest of ur string.See here https://regex101.com/r/hI0qP0/17 – vks Jun 13 '15 at 22:39
2

You should use anchors and negative lookahead:

^(?!.*?myword).*$

(?!.*?myword) is a negative lookahead that will fail the match if myword is found anywhere in the input string.

anubhava
  • 761,203
  • 64
  • 569
  • 643