using negate in ruby regex
In Ruby regular expressions, the ^ character is used to denote the beginning of the String. The the following…
a = 'abcde' s.match(/^a/)
…returns true/makes a match because the string s begins with the character “a”. But if you want to match on all characters that are not “a”, how do you do it?
s.match(/[^a]/)
Once ^a is placed inside of the square brackets it becomes a character class where the ^ character acts as negation rather than beginning-of-string.
I’m sure most people who pay attention picked this up the first time reading through a Ruby book, but I don’t pay 100% attention all the time and this minor detail slipped by.


March 2nd, 2007 at 6:09 pm
Regular expressions remain for me a dark science. Certain things eventually stick in my head after repeated use, while others require me to go Googling.
The ^ thing was a recent memory acquisition for me.
One nice thing is that there are many regex help pages on the Web. But beware; many of these are geared for perl, and there are a few differences from Ruby.
April 30th, 2007 at 2:59 am
The carrot sign doesn’t mean negate.. I’m fairly sure it means the line begins with and the $ sign means end.
irb(main):010:0> test = ‘line test’
=> “line test”
irb(main):011:0> test.match(/^line/)
=> #
irb(main):012:0>
irb(main):013:0> test.match(/test$/)
=> #
I’m trying to find out how to negate a regexp right now. I use these w/ grep and just negate grep (-v), but that doesn’t help a bit w/ ruby! Best of luck!
April 30th, 2007 at 4:25 pm
I think if you read the original post http://disjointthoughts.com/?p=143 Eric you might find the answer you’re looking for.