'How to use back references in kotlin regular expressions?
I'm trying to use a regular expression with back references in kotlin to replace the placeholders of a String in the following fashion:
Source: "This is a %s with %02d whatever"
Target: "This is a <s/> with <02d/> whatever"
So I'm looking for something like this but with a proper syntax, of course:
private fun escapePlaceHolders(text: String): String {
return """%([^ ]+?)""".toRegex().replace(text, "<\1/>")
}
Obviously this code doesn't even compile, let alone work. The problem is that I do not know how to use the back reference in the replace function, if it can be done at all.
Solution 1:[1]
The simplest way to do that is what Wiktor Stribi?ew described in the accepted answer.
There's a powerful alternative in case you need to not just reference but arbitrarily transform the matches for replacement, the replace
overload with the signature:
fun CharSequence.replace(regex: Regex, transform: (MatchResult) -> CharSequence): String
It can be used as follows:
"""%([^ ]+)""".toRegex().replace(text) { "<${it.groupValues[1]}/>" }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | hotkey |