Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions lib/elixir/lib/regex.ex
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,14 @@ defmodule Regex do
:re.replace(string, compiled, replacement, opts)
end

{ :ok, pattern } = :re.compile(%B"[.^$*+?()[{\\\\|]")
@escape_pattern pattern

@spec escape(String.t | char_list) :: String.t | char_list
def escape(string) do
:re.replace(string, @escape_pattern, "\\\\&", [:global, { :return, return_for(string) }])
end

# Helpers

@doc false
Expand Down
21 changes: 21 additions & 0 deletions lib/elixir/test/elixir/regex_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,27 @@ defmodule Regex.BinaryTest do
assert Regex.replace(%r(b), "abcbe", "[\\&]") == "a[&]c[&]e"
assert Regex.replace(%r[(b)], "abcbe", "[\\1]") == "a[b]c[b]e"
end

test :escape do
assert escaping(".", ".")
refute escaping(".", "x")

assert escaping("[\w]", "[\w]")
refute escaping("[\w]", "x")

assert escaping("\\", "\\")

assert escaping("\\xff", "\\xff")
refute escaping("\\xff", "\xff")

assert escaping("(", "(")
assert escaping("()", "()")
assert escaping("(?:foo)", "(?:foo)")
end

defp escaping(string, match) do
Regex.match? %r/#{Regex.escape(string)}/, match
end
end

defmodule Regex.ListTest do
Expand Down