Skip to content

Instantly share code, notes, and snippets.

@ryanmiville
Last active November 21, 2024 19:36
Show Gist options
  • Save ryanmiville/9ad47c3700964f78e6724cef2a04abe4 to your computer and use it in GitHub Desktop.
Save ryanmiville/9ad47c3700964f78e6724cef2a04abe4 to your computer and use it in GitHub Desktop.
Gleam replace regex match
import gleam/io
import gleam/list
import gleam/option.{Some}
import gleam/regex.{type Match, type Regex}
import gleam/string
pub fn replace_match(
each pattern: Regex,
in string: String,
with substitute: fn(Match) -> String,
) -> String {
let matches = regex.scan(pattern, string)
let replacements = list.map(matches, fn(m) { #(m.content, substitute(m)) })
list.fold(replacements, string, fn(acc, replacement) {
let #(p, s) = replacement
string.replace(acc, p, s)
})
}
const input = "
@('hello')
@('world')
"
pub fn main() {
let assert Ok(re) = regex.from_string("@\\('([^']*)'\\)")
replace(each: re, in: input, with: substitute)
|> io.println
//
// HELLO
// WORLD
//
}
fn substitute(match: Match) -> String {
let assert [Some(s)] = match.submatches
string.uppercase(s)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment