regex AND operator with negative arguments

804 views Asked by At

I'm trying to match lines that doesn't end with either . or ! and doesn't end with either ." or !" so it should match both

  • say "bye"
  • say "bye

but shouldn't match:

  • say "bye.
  • say "bye!
  • say "bye."
  • say "bye!"

I tried using positive and negative lookahead, trying to use them as AND as suggested in Regex AND operator, but I can't make it work, nor I'm sure it's feasible with lookaheads.

3

There are 3 answers

7
Vampire On BEST ANSWER

Just use a negative lookbehind. This matches exactly what you asked for: ^.*+(?<![.!]"?)$


^ - beginning of line
.*+ - any amount of characters, not giving up for backtracking
(?<! + ) - not preceded by
[.!] - dot or exclamation mark
"? - optional double-quote
$ - end of line

4
Mathias R. Jessen On

Ensure bye isn't succeeded by . or ! with a positive look-ahead for a negative character class, and then make the last " optional with the ? quantifier:

\bsay "bye(?=[^.!])"?
1
Code Maniac On

You can use

^(?!.*[.!]"?$).*$

enter image description here

Regex Demo

Note:- This matches empty line too as we use * which means match anything zero or more time, if you want to avoid empty lines to match you can use + quantifier which means match one or more time