zpearce
06/27/2018, 5:15 PMfun main(vararg args: String) {
val msg = "The amount is 500"
val regex = "The amount is (?<num>[0-9]+)".toRegex()
val num = regex.matchEntire(msg)?.groups?.get("num")?.value
val newMsg = "The amount is \$$num"
println(msg.replace(regex, newMsg))
}
My messages I'm trying to replace aren't this simple, but this code shows the gist of what I'm trying to do. I just need to grab a number out of a string, put it in a new string with a dollar sign in front of it, and replace part of the old string with the new string. However, I get:
Exception in thread "main" java.lang.IndexOutOfBoundsException: No group 5
at java.util.regex.Matcher.start(Matcher.java:375)
at java.util.regex.Matcher.appendReplacement(Matcher.java:880)
at java.util.regex.Matcher.replaceAll(Matcher.java:955)
at kotlin.text.Regex.replace(Regex.kt:144)
at MainKt.main(Main.kt:6)
I've tried raw strings, unicode code points, everything, but I can't get around this error. As soon as I take the escaped dollar sign out, there's no error. Seems like it might be a bug...