Home > OS >  Kotlin - How to split the string into digits and string?
Kotlin - How to split the string into digits and string?

Time:10-11

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"

CodePudding user response:

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
  • The | 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.

CodePudding user response:

this code also works well in this example:

val str = "Buy these 2 products and get 100 off"
val result = str.split(regex = Regex("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)"))
  • Related