Skip to content

Commit

Permalink
Escape backslashes in search and replacement
Browse files Browse the repository at this point in the history
  • Loading branch information
lens0021 committed Nov 24, 2024
1 parent 6d1b2f1 commit fe41a00
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 3 deletions.
8 changes: 6 additions & 2 deletions src/std/text.ab
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
/// Replaces all occurrences of a pattern in the content with the provided replace text.
pub fun replace(source, search, replace) {
return "\$\{source//{search}/{replace}}"
search = trust $ echo \$\{{nameof search}//\\\\/\\\\\\\\} $
replace = trust $ echo \$\{{nameof replace}//\\\\/\\\\\\\\} $
return trust $ echo \$\{{nameof source}//{search}/{replace}} $
}

/// Replaces the first occurrence of a pattern in the content with the provided replace text.
pub fun replace_once(source, search, replace) {
return "\$\{source/{search}/{replace}}"
search = replace(search, "\\", "\\\\")
replace = replace(replace, "\\", "\\\\")
return trust $ echo \$\{{nameof source}/{search}/{replace}} $
}

/// Replaces all occurrences of a regex pattern in the content with the provided replace text.
Expand Down
2 changes: 2 additions & 0 deletions src/tests/stdlib/replace.ab
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ import * from "std/text"

// Output
// apple apple
// apple

main {
echo replace("banana banana", "banana", "apple")
echo replace("\\", "\\", "apple")
}
2 changes: 1 addition & 1 deletion src/tests/stdlib/replace_once.ab
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * from "std/text"
main {
echo replace_once("Succinctly", "inctly", "eeded")
echo replace_once("Succinctly\\", "inctly\\", "eeded")
}

0 comments on commit fe41a00

Please sign in to comment.