eagspoo
eagspoo

Reputation: 2135

Why $ doesn't match \r\n

Can someone explain this:

str = "hi there\r\n\r\nfoo bar"

rgx = /hi there$/
str.match rgx # => nil

rgx = /hi there\s*$/
str.match rgx # => #<MatchData "hi there\r\n\r">

On the one hand it seems like $ does not match \r. But then if I first capture all the white spaces, which also include \r, then $ suddenly does appear to match the second \r, not continuing to capture the trailing "\nfoo bar".

Is there some special rule here about consecutive \r\n sequences? The docs on $ simply say it will match "end of line" which doesn't explain this behavior.

Upvotes: 1

Views: 77

Answers (1)

hobbs
hobbs

Reputation: 239781

$ is a zero-width assertion. It doesn't match any character, it matches at a position. Namely, it matches either immediately before a \n, or at the end of string.

/hi there\s*$/ matches because \s* matches "\r\n\r", which allows the $ to match at the position before the second \n. The $ could have also matched at the position before the first \n, but the \s* is greedy and matches as much as it can, while still allowing the overall regex to match.

Upvotes: 4

Related Questions