newline and regular expressions

T

tsuraan

I have a string "foo\nbar=3Dblah", which I'd like to entirely replace
with "baz=3Dblah". Supposedly, the regular expression constructed with
/.../i will match newlines, but it doesn't seem to work:
str =3D "foo\nbar=3Dblah" =3D> "foo\nbar=3Dblah"
str.sub(/.*bar/i, 'baz') =3D> "foo\nbaz=3Dblah"
str.sub(/\A.*bar/i, 'baz')
=3D> "foo\nbar=3Dblah"

Is there any way to do this? Does the /.../i really do what I think
it should do?
 
B

Brian Schröder

I have a string "foo\nbar=3Dblah", which I'd like to entirely replace
with "baz=3Dblah". Supposedly, the regular expression constructed with
/.../i will match newlines, but it doesn't seem to work:
=20
=3D> "foo\nbar=3Dblah"
=20
Is there any way to do this? Does the /.../i really do what I think
it should do?
=20
=20

/i makes the regexp case insensitve, use /m for multiline e.g. dot
matches newline.

irb(main):001:0> "test\nit".gsub /./, 'X'
=3D> "XXXX\nXX"
irb(main):002:0> "test\nit".gsub /./m, 'X'
=3D> "XXXXXXX"

regards,

Brian

--=20
http://ruby.brian-schroeder.de/

Stringed instrument chords: http://chordlist.brian-schroeder.de/
 
T

tsuraan

I guess I meant /.../s, which one site said was " '.' matches newline
mode", but anyhow, that works great. Thanks!
 
B

Brian Candler

I guess I meant /.../s, which one site said was " '.' matches newline
mode", but anyhow, that works great. Thanks!

WARNING!! Ruby and Perl are very different here; don't try to follow Perl
documentation on regular expressions.

Ruby: /foo/ = Perl: /foo/m

Ruby: /foo/m = Perl: /foo/ms

In Ruby, /foo/s means match the string with Shift-JIS (Japanese encoding),
which is quite likely not what you want :)

(Unfortunately, I don't think ri documents regexp patterns and modifiers,
unlike perl's "man perlre". I end up referring to the Pickaxe book p324 for
this)

There is no way to turn off the equivalent of Perl's /m flag. This is
important if you are using regexps to validate data: ^ and $ do not just
match the start and end of string, they also match at newlines (\n).

foo.untaint if foo =~ /^[a-z]*$/ # DANGEROUS

foo.untaint if foo =~ /\A[a-z]*\z/ # correct

Regards,

Brian.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top