Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kotlin String::replace removing escape sequences?

I'm trying some string manipulation using regex's, but I'm not getting the expected output

var myString = "/api/<user_id:int>/"
myString.replace(Regex("<user_id:int>"), "(\\d+)")

this should give me something like /api/(\d+)/ but instead I get /api/(d+)/

However if I create an escaped string directly like var a = "\d+"
I get the correct output \d+ (that I can further use to create a regex Pattern)
is this due to the way String::replace works?
if so, isn't this a bug, why is it removing my escape sequences?

like image 461
Ishan Khare Avatar asked Dec 18 '22 00:12

Ishan Khare


1 Answers

To make the replace a literal string, use:

myString.replace(Regex("<user_id:int>"), Regex.escapeReplacement("(\\d+)"))

For details, this is what kotlin Regex.replace is doing:

  Pattern nativePattern = Pattern.compile("<user_id:int>");
  String m = nativePattern.matcher("/api/<user_id:int>/").replaceAll("(\\d+)");

  -> m = (d+) 

From Matcher.replaceAll() javadoc:

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. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string.

The call to Regex.escapeReplacement above does exactly that, turning (\\d+) to (\\\\d+)

like image 63
guido Avatar answered Dec 27 '22 18:12

guido