Why is that a thing in Kotlin? ```val url = "<http...
# announcements
g
Why is that a thing in Kotlin?
Copy code
val url = "<https://google.com/>"
val rgxReplace = url.replace("/".toRegex(), "\\/")
val strReplace = url.replace("/", "\\/")
    
println(rgxReplace)  // outputs: <https://google.com/>
println(strReplace)  // outputs: https:\/\/google.com\/
In the regex example I should replace with
"\\\\/"
to get a similar result
r
You have to deal with 2 levels of character escaping: 1 for the string literal, and 1 for the regex.
👍 1
👆 2
g
So it expects the replacing to also be a regex? In what use case would that be a thing?
Another thing, I'm writing something like that to implement escaping for the
/
character in Gson serialization. My backend needs that, although I'm slightly concerned about possible side effects like breaking Base64.
r
To get a literal
\
in regex, you need to escape it:
\\
. To get a literal
\\
in a Kotlin string, you need to escape both:
\\\\
.
v
@gabrielfv You can use raw-strings to avoid double-escaping: https://kotlinlang.org/docs/reference/basic-types.html#string-literals
Copy code
url.replace("/".toRegex(), """\\/""")
2