Match just the beginning of a string in a Ruby regex

I have a string variable with several newlines, and I would like to check if the beginning of the string matches the regular expression. However, when I use the ^ character, it matches the text that starts with each new line.

I want this to fit:

 "foo\nbar" =~ /^foo/ 

and I want it to not match

 "bar\nfoo" =~ /^foo/ 

I can not find a modifier that makes the ^ character (or any other) match only the beginning of the line. Any help was greatly appreciated.

+7
ruby regex
source share
2 answers

In Ruby, carriage and dollar always match before and after newlines. Ruby does not have a modifier to change this. Use \ A and \ Z to match at the beginning or end of a line.

See: http://www.regular-expressions.info/ruby.html

+12
source share

From "Ruby Programming"

 '\A Matches the beginning of the string. ' 
+1
source share

All Articles