Is the multiline modifier for regexes on by default?

It looks like the m multiline modifier for regex is on by default?

iex(17)> Regex.match?(~r/^foo$/, "foo\n")
true
iex(18)> Regex.match?(~r/^foo$/m, "foo\n")
true

I would expect the first case to fail because the multiline modifier is disabled? I know I can use \z but that it is still not clear why the first regex matches.

It becomes relevant when you have more than a single line. Single line mode wont try to match in subsequent lines, multi line mode does:

iex(1)> Regex.match?(~r/^bar$/, "foo\nbar\n")
false
iex(2)> Regex.match?(~r/^bar$/m, "foo\nbar\n")
true
2 Likes

Hmm, I was comparing with the javascript regex where this is not the case:

"foo\n".match(/^foo$/)
null
"foo\n".match(/^foo$/m)
Array [ "foo" ]

It seems logically that $ would not match on \n when multiline is disabled.

The way elixir does it is consistent with how perl does.

2 Likes

It’s also worth pointing out that if you actually want to match across lines, you’ll need the “dotall” s modifier:

Regex.match?(~r/^bar$/s, some_multiline_string)

2 Likes