diff --git a/src/gleam/regex.gleam b/src/gleam/regex.gleam index d1f8ef0a..fc61506d 100644 --- a/src/gleam/regex.gleam +++ b/src/gleam/regex.gleam @@ -3,7 +3,9 @@ //// all of the PCRE library is interfaced and some parts of the library go beyond //// what PCRE offers. Currently PCRE version 8.40 (release date 2017-01-11) is used. +import gleam/list import gleam/option.{type Option} +import gleam/string pub type Regex @@ -214,3 +216,23 @@ pub fn replace( in string: String, with substitute: String, ) -> String + +/// Escapes all `Regex` characters in a given `String`. +/// +/// ## Examples +/// +/// ```gleam +/// regex.escape("hello$world^test") +/// // -> "hello\\$world\\^test" +/// ``` +/// +/// ```gleam +/// regex.escape("$^.*+?()[]{}|\\") +/// // -> "\\$\\^\\.\\*\\+\\?\\(\\)\\[\\]\\{\\}\\|\\\\" +/// ``` +pub fn escape(input: String) -> String { + ["\\", "$", "^", ".", "*", "+", "?", "(", ")", "[", "]", "{", "}", "|"] + |> list.fold(input, fn(acc, char) { + string.replace(in: acc, each: char, with: "\\" <> char) + }) +} diff --git a/test/gleam/regex_test.gleam b/test/gleam/regex_test.gleam index e5175779..793d86e6 100644 --- a/test/gleam/regex_test.gleam +++ b/test/gleam/regex_test.gleam @@ -185,3 +185,28 @@ pub fn replace_3_test() { regex.replace(re, "🐈🐈 are great!", "🐕") |> should.equal("🐕🐕 are great!") } + +pub fn escape_test() { + // Test escaping common regex symbols + let input = "$^.*+?()[]{}|\\" + let expected = "\\$\\^\\.\\*\\+\\?\\(\\)\\[\\]\\{\\}\\|\\\\" + input + |> regex.escape + |> should.equal(expected) +} + +pub fn escape_no_special_chars_test() { + let input = "hello" + let expected = "hello" + input + |> regex.escape + |> should.equal(expected) +} + +pub fn escape_mixed_string_test() { + let input = "hello$world^test" + let expected = "hello\\$world\\^test" + input + |> regex.escape + |> should.equal(expected) +}