Skip to content

Commit ac0ac7f

Browse files
author
José Valim
committed
Merge pull request #1153 from meh/regex-escape
Implement Regex.escape
2 parents fe97c48 + 5ff3b76 commit ac0ac7f

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

lib/elixir/lib/regex.ex

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,14 @@ defmodule Regex do
291291
:re.replace(string, compiled, replacement, opts)
292292
end
293293

294+
{ :ok, pattern } = :re.compile(%B"[.^$*+?()[{\\\\|]")
295+
@escape_pattern pattern
296+
297+
@spec escape(String.t | char_list) :: String.t | char_list
298+
def escape(string) do
299+
:re.replace(string, @escape_pattern, "\\\\&", [:global, { :return, return_for(string) }])
300+
end
301+
294302
# Helpers
295303

296304
@doc false

lib/elixir/test/elixir/regex_test.exs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,27 @@ defmodule Regex.BinaryTest do
127127
assert Regex.replace(%r(b), "abcbe", "[\\&]") == "a[&]c[&]e"
128128
assert Regex.replace(%r[(b)], "abcbe", "[\\1]") == "a[b]c[b]e"
129129
end
130+
131+
test :escape do
132+
assert escaping(".", ".")
133+
refute escaping(".", "x")
134+
135+
assert escaping("[\w]", "[\w]")
136+
refute escaping("[\w]", "x")
137+
138+
assert escaping("\\", "\\")
139+
140+
assert escaping("\\xff", "\\xff")
141+
refute escaping("\\xff", "\xff")
142+
143+
assert escaping("(", "(")
144+
assert escaping("()", "()")
145+
assert escaping("(?:foo)", "(?:foo)")
146+
end
147+
148+
defp escaping(string, match) do
149+
Regex.match? %r/#{Regex.escape(string)}/, match
150+
end
130151
end
131152

132153
defmodule Regex.ListTest do

0 commit comments

Comments
 (0)