Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add regex.escape #691

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
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
22 changes: 22 additions & 0 deletions src/gleam/regex.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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)
})
}
25 changes: 25 additions & 0 deletions test/gleam/regex_test.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}