Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match newline `\n` in ruby regex

Tags:

regex

ruby

I'm trying to understand why the following returns false: (** I should have put "outputs 0" **)

puts "a\nb" =~ Regexp.new(Regexp.escape("a\nb"), Regexp::MULTILINE | Regexp::EXTENDED)

Perhaps someone could explain.

I am trying to generate a Regexp from a multi-line String that will match the String.

Thanks in advance

like image 994
Arth Avatar asked Sep 05 '12 12:09

Arth


People also ask

How do you match a new line in regex?

"\n" matches a newline character.

What is \r and \n in regex?

Regex recognizes common escape sequences such as \n for newline, \t for tab, \r for carriage-return, \nnn for a up to 3-digit octal number, \xhh for a two-digit hex code, \uhhhh for a 4-digit Unicode, \uhhhhhhhh for a 8-digit Unicode.

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.

Does dot match newline regex?

By default, a dot matches any character, except for the newline. That default can be changed to add matching the newline by using the single line modifier: for the entire regular expression with the /s modifier, or locally with (? s) (and even globally within the scope of use re '/s' ).


1 Answers

puts will always return nil.

Your code should work fine, albeit lengthy. =~ returns the position of the match which is 0.

You could also use:

"a\nb" =~ /a\sb/m

or

"a\nb" =~ /a\nb/m

Note: The m option isn't necessary in this example but demonstrates how it would be used without Regexp.new.

like image 151
Brian Ustas Avatar answered Sep 29 '22 21:09

Brian Ustas