I am currently facing an issue in my android app when trying to search and replace a string.
I receive a sentence which contain the keyword ${keyword}
it's coming like Today we are ${keyword} and it is beautiful
I have to parse it and replace ${keyword}
by a specific string
below is my code:
const val PATTERN_TO_FIND = "\${keyword}"
private val keywordRegex = Regex(ContentfulTranslations.PATTERN_TO_FIND)
fun replaceMyKeyword(sentence: String): String{
return sentence.replace(keywordRegex, "blabla")
}
The app keeps crashing when parsing the sentence and looking for the pattern.
I already use this method and it used to work but the pattern to find wasn't formatted as ${keyword}
Any idea?
Thanks
The reason why it's crashing is that curly braces are reserved characters in regexp indicating a range, so you need to escape them (or at least the opening one).
Moreover, \$
will put a literal $
sign at the beginning of your regexp, but dollar sign indicates the end of the string to match, so you need to "regexp-escape" it as well.. The end result would be:
const val PATTERN_TO_FIND = "\\\$\\{keyword}"
Luckily, Pattern
class offers a utility method to automatically escape a regexp:
val pattern = Pattern.quote("\${keyword}")
Note that you still need to escape the dollar sign because it has a special meaning in Kotlin.
A full working example:
fun main() {
val s = "Today we are \${keyword} and it is beautiful"
val pattern = Pattern.quote("\${keyword}")
val keywordRegex = Regex(pattern)
println(s.replace(keywordRegex, "blabla"))
}
Will print:
Today we are blabla and it is beautiful