Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match only beginning of line in Ruby regexp

Tags:

regex

ruby

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.

like image 998
cabird Avatar asked Jan 20 '10 19:01

cabird


People also ask

How do you match a string at the the beginning of a line?

The \A anchor specifies that a match must occur at the beginning of the input string. It is identical to the ^ anchor, except that \A ignores the RegexOptions. Multiline option. Therefore, it can only match the start of the first line in a multiline input string.

What does =~ mean in Ruby RegEx?

=~ is Ruby's basic pattern-matching operator. When one operand is a regular expression and the other is a string then the regular expression is used as a pattern to match against the string. (This operator is equivalently defined by Regexp and String so the order of String and Regexp do not matter.

How do you match line breaks in RegEx?

Line breaks In pattern matching, the symbols “^” and “$” match the beginning and end of the full file, not the beginning and end of a line. If you want to indicate a line break when you construct your RegEx, use the sequence “\r\n”.

What does \b mean in RegEx?

The word boundary \b matches positions where one side is a word character (usually a letter, digit or underscore—but see below for variations across engines) and the other side is not a word character (for instance, it may be the beginning of the string or a space character).


1 Answers

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

like image 79
Bart Kiers Avatar answered Oct 05 '22 19:10

Bart Kiers