Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex AND operator with negative arguments

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.

like image 924
Mauro Avatar asked Aug 17 '19 11:08

Mauro


People also ask

How do you use negation in regex?

Similarly, the negation variant of the character class is defined as "[^ ]" (with ^ within the square braces), it matches a single character which is not in the specified or set of possible characters. For example the regular expression [^abc] matches a single character except a or, b or, c.

What is difference [] and () in regex?

In other words, square brackets match exactly one character. (a-z0-9) will match two characters, the first is one of abcdefghijklmnopqrstuvwxyz , the second is one of 0123456789 , just as if the parenthesis weren't there. The () will allow you to read exactly which characters were matched.

What is negative look ahead in regex?

3.2. A negative look-ahead, on the other hand, is when you want to find an expression A that does not have an expression B (i.e., the pattern) after it. Its syntax is: A(?!B) . In a way, it is the opposite of a positive look-ahead.

What is '?' In regular expression?

'?' matches/verifies the zero or single occurrence of the group preceding it. Check Mobile number example. Same goes with '*' . It will check zero or more occurrences of group preceding it.


2 Answers

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

like image 162
Code Maniac Avatar answered Nov 15 '22 07:11

Code Maniac


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

like image 35
Vampire Avatar answered Nov 15 '22 08:11

Vampire