I want to split a long string (containing digits and characters) into different substrings in Kotlin?
eg:- Buy these 2 products and get 100 off
output needed -> "Buy these ","2 ","products and get ","100 ","off"
I want to split a long string (containing digits and characters) into different substrings in Kotlin?
eg:- Buy these 2 products and get 100 off
output needed -> "Buy these ","2 ","products and get ","100 ","off"
Use a regular expression that will match either a group of digits, or a group of non-digit characters.
I used \d+|\D+.
\d+ will match groups of digits, like 2 and 100\D+ will match any sequence of characters that doesn't contain digits| indicates that the pattern should match either \d+ or \D+Use findAll to find each part of the string that matches the pattern.
val regex = Regex("""\d+|\D+""")
val input = "Buy these 2 products and get 100 off"
val result = regex.findAll(input).map { it.groupValues.first() }.toList()
The result I get is:
["Buy these ", "2", " products and get ", "100", " off"]
The spacing isn't quite the same as what you're looking for, so you could trim the results, or adjust the regex pattern.