Sunday, September 7, 2008

Finding The Opposite Of A Regular Expression In Ruby

I don't know if it happened to you but there are some times when you want to find the contrary of what you have in mind, I mean the opposite (inverse) of a regular expression or everything except a certain regexp. Well, there is a way to achieve that with Ruby (and a lot of other programming languages):
/^((?!REGULAR_EXPRESSION_HERE).)*$/


For example, if you want to find every lines where the first character is NOT 2 to 4 "f" followed by "oo" and then "bar" somewhere else on the line, you can use:
/^((?!^f{2,4}oo.*bar).)*$/

Example:
"foo+bar"[/^((?!^f{2,4}oo.*bar).)*$/] => "foo+bar"

"fffoo+bar"[/^((?!^f{2,4}oo.*bar).)*$/] => nil

" fffoo+bar"[/^((?!^f{2,4}oo.*bar).)*$/] => " fffoo+bar"

"fffffoo+bar"[/^((?!^f{2,4}oo.*bar).)*$/] => "fffffoo+bar"


For the references, those ideas came from the Vim tips section here.

I hope this will help someone.