Last active
November 21, 2024 19:36
-
-
Save ryanmiville/9ad47c3700964f78e6724cef2a04abe4 to your computer and use it in GitHub Desktop.
Gleam replace regex match
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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