Fork me on GitHub
#clojure
<
2023-11-28
>
Ingy döt Net11:11:11

user=> (str/replace "foo \\$bar baz" #"\\\$" "X")
"foo Xbar baz"
user=> (str/replace "foo \\$bar baz" #"\\\$" "$")
Execution error (IllegalArgumentException) at java.util.regex.Matcher/appendExpandedReplacement (Matcher.java:1075).
Illegal group reference: group index is missing

user=> (str/replace "foo \\$bar baz" #"\\\$" "\$")
Syntax error reading source at (REPL:1:42).
Unsupported escape character: \$

user=> (str/replace "foo \\$bar baz" #"\\\$" "\u0024")
Execution error (IllegalArgumentException) at java.util.regex.Matcher/appendExpandedReplacement (Matcher.java:1075).
Illegal group reference: group index is missing

user=> (str/replace "foo \\$bar baz" #"\\\$" (str \$))
Execution error (IllegalArgumentException) at java.util.regex.Matcher/appendExpandedReplacement (Matcher.java:1075).
Illegal group reference: group index is missing

user=> 
How can I do this?

Ingy döt Net11:11:36

answer:

user=> (str/replace "foo \\$bar baz" #"\\(\$)" "$1")
"foo $bar baz"

Ingy döt Net11:11:52

for this case. but how would I replace say all #"\+.*?\+" patterns with "$" ?

tomd11:11:41

(str/replace "foo \\$bar baz" #"\\\$" "\\$")
;; => "foo $bar baz"
seems to work for me

👍 3
phill11:11:18

The Java platform's peculiarities might be shining through. Javadoc (https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#replaceAll-java.lang.String-java.lang.String-) says "Note that backslashes (`\`) and dollar signs (`$`) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher.replaceAll. Use Matcher.quoteReplacement(java.lang.String) to suppress the special meaning of these characters, if desired."

😲 1
👍 2
Ingy döt Net11:11:53

Definitely felt like something at the java level. Thanks all!

Ingy döt Net11:11:35

(str/replace "foo \\$bar baz" #"\\\$" (str/re-quote-replacement "$"
))
;; => "foo $bar baz"
I use str/re-quote-replacement for more complex regex combinating but wouldn't have that to use it here. thanks.

👍 1