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.
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.
=~ 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.
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”.
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With