cabird
cabird

Reputation: 541

Match only beginning of line in Ruby regexp

I have a string variable that has multiple newlines in it and I'd like to test if the beginning of the string matches a regular expression. However, when I use the ^ character, it matches against text that begins at each newline.

I want this to match:

"foo\nbar" =~ /^foo/

and I want this to not match

"bar\nfoo" =~ /^foo/

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

Upvotes: 8

Views: 6178

Answers (2)

AShelly
AShelly

Reputation: 35520

From "Programming Ruby"

'\A 
   Matches the beginning of the string. '

Upvotes: 1

Bart Kiers
Bart Kiers

Reputation: 170148

In Ruby, the caret 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 start or the end of the string.

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

Upvotes: 12

Related Questions