2

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"

3
  • 1
    This looks like a line from a CSV file. If so, it's usually better to use an existing library to parse it — not only do you not have to muck around with regexes or whatever, but the library will cope with nested quotes, escape characters, comments, locale-specific separators, and all the other variations and corner cases and complications that you haven't thought of. (For example, Apache Commons CSV is free and open-source.) Commented Oct 10, 2021 at 21:12
  • I prefer to use answer by @Sam Commented Oct 11, 2021 at 15:18
  • also the answer by @Alireza Mahfouzian Commented Oct 11, 2021 at 15:18

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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)"))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.