Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby regex: ^ matches start of line even without m modifier?

Tags:

regex

ruby

Ruby 1.8.7. I'm using a regex with a ^ to match a pattern at the start of the string. The problem is that if the pattern is found at the start of any line in the string it still matches. This is the behaviour I would expect if I were using the 'm' modifier but I'm not:

$ irb
irb(main):001:0> str = "hello\ngoodbye"
=> "hello\ngoodbye"
irb(main):002:0> puts str
hello
goodbye
=> nil
irb(main):004:0> str =~ /^goodbye/
=> 6

What am I doing wrong here?

like image 218
SteveRawlinson Avatar asked Nov 23 '10 14:11

SteveRawlinson


1 Answers

Your confusion is justified. In most regex flavors, ^ is equivalent to \A and $ is equivalent to \Z by default, and you have to set the "multiline" flag to make them take on their other meanings (i.e. line boundaries). In Ruby, ^ and $ always match at line boundaries.

To add to the confusion, Ruby has something it calls "multiline" mode, but it's really what everybody else calls "single-line" or "DOTALL" mode: it changes the meaning of the . metacharacter, allowing it to match line-separator characters (e.g. \r, \n) as well as all other characters.

like image 127
Alan Moore Avatar answered Oct 04 '22 10:10

Alan Moore