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
"\n" matches a newline character.
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.
=~ 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.
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' ).
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
.
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