1

Surprisingly the regex matcher does not match backslash correcly. For example

Regex.split(~r{\\}, "C:\foo\bar")
["C:\foo\bar"]
Regex.match?(~r/\\/, "C:\foo\bar")
false

I would expect a positive match, but maybe I'm escaping \ wrong. Let's test that out:

Regex.escape("\\")
"\\\\"
Regex.split(~r{\\\\}, "C:\foo\bar")
["C:\foo\bar"]
Regex.match?(~r/\\\\/, "C:\foo\bar")
false

Still no match. Fairly confused at this point. How do you escape \ in a regex to match a literal \ as you can see in my usecase I would like to split a windows path.

Arijoon
  • 2,184
  • 3
  • 24
  • 32
  • What does `Regex.split(~r{\}, "C:\foo\bar")` produce? – MonkeyZeus Feb 05 '20 at 16:02
  • @MonkeyZeus obviously it does not produce anything, it cannot be parsed because the closing parenthesis is still inside a regular expression, opened with `~r{` and never closed (closing curly is escaped with a backslash.) – Aleksei Matiushkin Feb 05 '20 at 18:02
  • Another option (since I'm guessing you're using Windows) is "C:/foo/bar" Forward slashes do work on Windows but there are odd little gotcha's to be aware of. – Onorio Catenacci Feb 06 '20 at 13:39

1 Answers1

3

Regex is fine; your input is not what you think it is. Backslash inside strings escapes.

String.split("C:\foo\bar", "")
#⇒ ["", "C", ":", "\f", "o", "o", "\b", "a", "r", ""]

String.length("C:\foo\bar")
#⇒ 8

Note "\f" and "\b" there. The string contains no backslash, but it contains "\f" and "\b" codepoints.

That said, you need to pass a proper string to Regex.split/3 to yield the expected result.

Regex.split(~r|\\|, "C:\\foo\\bar")
#⇒ ["C:", "foo", "bar"]
Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160