multiline regexp and newlines

M

Markus Schirp

Hello Community,

Im trying to reject any newline in a string using regexp.
The string must not be empty.

Yes, this can be done without regexp.

So my Regexp is like:

"Match any character from the begin to the end of a string witch is not
newline, and ensure there is at least one character, and to this match
over multiple lines (so if there are multiple lines reject it)"

Results in /^[^\n]+$/m

My ruby 1.8.6 does:

/^[^\n]+$/m =~ "a\n" -> 0

without multiline flag the same:

/^[^\n]+$/ =~ "a\n" -> 0

But:

/^[^\n]+$/m =~ "\n" -> nil

If I replace "reject newline" with "reject character x" it worked as
expected (x is 'a' in this example):

/^[^a]+$/m =~ "ba" -> nil

Is the multiline-regexp implementation broken or my multiline behaviour
expectation?

Mfg

Markus Schirp
 
D

Daniel DeLorme

Markus said:
So my Regexp is like:

"Match any character from the begin to the end of a string witch is not
newline, and ensure there is at least one character, and to this match
over multiple lines (so if there are multiple lines reject it)"

Results in /^[^\n]+$/m

My ruby 1.8.6 does:

/^[^\n]+$/m =~ "a\n" -> 0

without multiline flag the same:

/^[^\n]+$/ =~ "a\n" -> 0

The multiline flag only changes the meaning of "." to include the \n
character. It doesn't change the meaning of ^ and $ which mean
respectively "beginning of line" and "end of line". True true "beginning
of string" metacharacter is not ^ but \A, and for "end of string" it's
not $ but \z (or \Z if you want to allow a trailing \n on your string)
"a\nb\n"[ /^.*$/ ] => "a"
"a\nb\n"[ /\A.*\z/ ] => nil
"a\nb\n"[ /\A.*\z/m ]
=> "a\nb\n"

Yeah, it's tricky.
 
M

Markus Schirp

Markus said:
So my Regexp is like:
"Match any character from the begin to the end of a string witch is not
newline, and ensure there is at least one character, and to this match
over multiple lines (so if there are multiple lines reject it)"
Results in /^[^\n]+$/m
My ruby 1.8.6 does:
/^[^\n]+$/m =~ "a\n" -> 0
without multiline flag the same:
/^[^\n]+$/ =~ "a\n" -> 0

The multiline flag only changes the meaning of "." to include the \n
character. It doesn't change the meaning of ^ and $ which mean respectively
"beginning of line" and "end of line". True true "beginning of string"
metacharacter is not ^ but \A, and for "end of string" it's not $ but \z
(or \Z if you want to allow a trailing \n on your string)
"a\nb\n"[ /^.*$/ ] => "a"
"a\nb\n"[ /\A.*\z/ ] => nil
"a\nb\n"[ /\A.*\z/m ]
=> "a\nb\n"

Yeah, it's tricky.

Thx, it works now!
 

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

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,906
Latest member
SkinfixSkintag

Latest Threads

Top