However if a create an escaped string directly lik...
# getting-started
i
However if a create an escaped string directly like
var a = "\d+"
i get the correct output
\d+
(that i can further use to create a regex Patter) is this due to the way
String::replace
works? if so, isn't this a bug, why is it removing my escape sequences?
n
The reason is that the replacement can contain references to capture groups from the regex, using e.g.
$1
. Now to add a literal
$
in the replacement, you thus have to quote the
$
using
\
. And because this
\
quoting is not limited to just looking at a following
$
, any \ that you want in the output needs to be doubled. Details are in
Matcher::appendReplacement
description which is internally used for all of this.
thus, correct code is
Copy code
var myString = "/api/<user_id:int>/"
myString.replace(Regex("<user_id:int>"), "(\\\\d+)")
or one of the the equivalent
Copy code
myString.replace(Regex("<user_id:int>"), """(\\d+)""")
Regex("<user_id:int>").replace(myString, , """(\\d+)""")