Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match anything EXCEPT this string?

Tags:

regex

ruby

How can I match a string that is NOT partners?

Here is what I have that matches partners:

/^partners$/i

I've tried the following to NOT match partners but doesn't seem to work:

/^(?!partners)$/i
like image 899
Jacob Avatar asked Dec 17 '22 05:12

Jacob


1 Answers

Your regex

/^(?!partners)$/i

only matches empty lines because you didn't include the end-of-line anchor in your lookahead assertion. Lookaheads do just that - they "look ahead" without actually matching any characters, so only lines that match the regex ^$ will succeed.

This would work:

/^(?!partners$)/i

This reports a match with any string (or, since we're in Ruby here, any line in a multi-line string) that's different from partners. Note that it only matches the empty string at the start of the line. Which is enough for validation purposes, but the match result will be "" (instead of nil which you'd get if the match failed entirely).

like image 198
Tim Pietzcker Avatar answered Dec 27 '22 16:12

Tim Pietzcker