3

I want to search for lines containing a certain word, book for example, and doesn't not contain car before it.

I've tried writing it like so :

[?!car].*book

But it doesn't work, so in these lines :

this car is a book
this is a book
book car

The first should not match, the other 2 should. What am I doing wrong?

https://regex101.com/r/L33d0h/1

  • Seems like you don't understand the meaning of your regex. Your regex matches the `?`, `!`, `c`, `a` **or** `r` character followed by any number of characters that is not a newline followed by `book`. Have a look at [Reference - What does this regex mean?](https://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean) – 3limin4t0r Apr 30 '19 at 09:58

1 Answers1

1

Here you have it

^(?:(?!car).)*book.*$

I used a non-capturing group to have a single full match for the Regex, but you can use it as you want.

The Regex you used searches the line for the first occurrence of any character in the character set [?!car]; this means ? and ! are treated as individual characters and not as a non capturing group as you may have otherwise intended. Following characters will be greedily captured unless book is encountered. That's why your Regex doesn't give you the required result.

Yassin Hajaj
  • 20,020
  • 9
  • 41
  • 81