Skip to content

Commit 5e94a69

Browse files
author
José Valim
committed
Merge pull request #1163 from meh/regex-escape
Support extended syntax in Regex.escape
2 parents 5775d49 + 3dd445b commit 5e94a69

File tree

2 files changed

+35
-13
lines changed

2 files changed

+35
-13
lines changed

lib/elixir/lib/regex.ex

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -291,9 +291,20 @@ defmodule Regex do
291291
:re.replace(string, compiled, replacement, opts)
292292
end
293293

294-
{ :ok, pattern } = :re.compile(%B"[.^$*+?()[{\\\\|]")
294+
{ :ok, pattern } = :re.compile(%B"[.^$*+?()[{\\\|\s#]", [:unicode])
295295
@escape_pattern pattern
296296

297+
@doc %B"""
298+
Escapes a string to be literally matched in a regex.
299+
300+
## Examples
301+
302+
iex> Regex.escape(".")
303+
"\\."
304+
iex> Regex.escape("\\what if")
305+
"\\\\what\\ if"
306+
307+
"""
297308
@spec escape(String.t | char_list) :: String.t | char_list
298309
def escape(string) do
299310
:re.replace(string, @escape_pattern, "\\\\&", [:global, { :return, return_for(string) }])

lib/elixir/test/elixir/regex_test.exs

Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -129,24 +129,35 @@ defmodule Regex.BinaryTest do
129129
end
130130

131131
test :escape do
132-
assert escaping(".", ".")
133-
refute escaping(".", "x")
132+
assert matches_escaped?(".")
133+
refute matches_escaped?(".", "x")
134134
135-
assert escaping("[\w]", "[\w]")
136-
refute escaping("[\w]", "x")
135+
assert matches_escaped?("[\w]")
136+
refute matches_escaped?("[\w]", "x")
137137
138-
assert escaping("\\", "\\")
138+
assert matches_escaped?("\\")
139139
140-
assert escaping("\\xff", "\\xff")
141-
refute escaping("\\xff", "\xff")
140+
assert matches_escaped?("\\xff", "\\xff")
141+
refute matches_escaped?("\\xff", "\xff")
142142
143-
assert escaping("(", "(")
144-
assert escaping("()", "()")
145-
assert escaping("(?:foo)", "(?:foo)")
143+
assert matches_escaped?("(")
144+
assert matches_escaped?("()")
145+
assert matches_escaped?("(?:foo)")
146+
147+
assert matches_escaped?("\\A \\z")
148+
assert matches_escaped?(" x ")
149+
assert matches_escaped?("  x    x ") # unicode spaces here
150+
assert matches_escaped?("# lol")
151+
152+
assert matches_escaped?("\\A.^$*+?()[{\\| \t\n\xff\\z #hello\x{202F}\x{205F}")
153+
end
154+
155+
defp matches_escaped?(string) do
156+
matches_escaped?(string, string)
146157
end
147158

148-
defp escaping(string, match) do
149-
Regex.match? %r/#{Regex.escape(string)}/, match
159+
defp matches_escaped?(string, match) do
160+
Regex.match? %r/#{Regex.escape(string)}/usimx, match
150161
end
151162
end
152163

0 commit comments

Comments
 (0)