KotlinLeaner
07/25/2023, 12:30 PMprivate const val BOLD_PATTERN = "<b>(.*?)</b>"
fun main() {
val message = "Hello, How are you? My Name is <b>Xyz</b>. <b>Abc</b> your next score will be 100 to win the game."
val itemList = findAndGetBoldList(message)
val filterMessage = message.replace("<b>", "").replace("</b>", "")
itemList.forEach { println("Bold part is :- $it") }
println(filterMessage)
}
fun findAndGetBoldList(message: String): List<String> {
return BOLD_PATTERN
.toRegex()
.findAll(message)
.map {
it.value.replace("<b>", "").replace("</b>", "")
}
.toList()
}
Szymon Jeziorski
07/31/2023, 6:50 AMconst val
, you can have the regex itself as a top level field - private val BOLD_PATTERN_REGEX = Regex("<b>(.*?)</b>")
since it is created the same way each time in findAndGetBoldList
.
Also, as you are using a captured group in your regex, you can use it to obtain the string being between <b>
opening and closing tags.
BOLD_PATTERN_REGEX
.findAll(message)
.map { it.groupValues[1] }
.toList()
This way is not only cleaner, but also it doesn't duplicate the tag name which is already in the regex. If you would like to change <b>
to <strong>
for example, above function would still work the same way as you don't have explicit replace
duplicating the tag name.
Another note is that within the main
function I would rename filterMessage
to filteredMessage
. filterMessage
to me sounds like a message used for filtering, whereas filtered
clearly indicates a message that has already been filtered. And again, here you can use Regex API to obtain filtered message instead of using String API for replacement duplicating tag names:
val filterMessage = BOLD_PATTERN_REGEX.replace(message, "$1")
- $1 indicates first captured group.
You can also use more verbose API providing replacement programatically:
BOLD_PATTERN_REGEX.replace(message) *{ it*.groupValues[1] *}*