Newline matching `\ n` in ruby ​​regex

I am trying to understand why the following returns false: (** I had to put "outputs 0" **)

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

Maybe someone can explain.

I am trying to create regexp from a multi-line string that will match String.

Thanks in advance

+5
source share
2 answers

putswill always return nil.

Your code should work fine, albeit a lengthy one. =~returns a match position that is 0.

You can also use:

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

or

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

Note. The parameter is mnot needed in this example, but demonstrates how it will be used without Regexp.new.

+9
source

It may have putscaused this

1.9.3-194 (main):0 > puts ("a\nb" =~ Regexp.new(Regexp.escape("a\nb"), Regexp::MULTILINE | Regexp::EXTENDED) )
0
=> nil


1.9.3-194 (main):0 > "a\nb" =~ Regexp.new(Regexp.escape("a\nb"), Regexp::MULTILINE | Regexp::EXTENDED)
=> 0
+1
source

All Articles