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.


4 Comments
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.
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!
I think if you read the original post http://disjointthoughts.com/?p=143 Eric you might find the answer you’re looking for.
Hi,
The post is misleading. The [^string] is not working as a negate in ruby 1.8.6. It’s simply searching for a string with a ‘^’ (literal).