3

I have the following string :

var myStr = "abc12ef4567gh90ijkl789"

The size of the list is not fixed and it contains number in between. I want to extract the numbers and store them in the form of a list in this manner:

List(12,4567,90,789)

I tried the solution mentioned here but cannot extend it to my case. I just want to know if there is any faster or efficient solution instead of just traversing the string and extracting the numbers one by one using brute force ? Also, the string can be arbitrary length.

0

1 Answer 1

12

It seems you may just collect the numbers using

("""\d+""".r findAllIn myStr).toList

See the Scala demo. \d+ matches one or more digits, findAllIn searches for multiple occurrences of the pattern inside a string (and also un-anchors the pattern so that partial matches could be found).

If you prefer a splitting approach, you might use

myStr.split("\\D+").filter(_.nonEmpty).toList

See another demo. Here, \D+ matches one or more non-digit chars, and these chunks are used to split on (texts between these chunks land in the result). .filter(_.nonEmpty) will remove empty items that usually appear due to matches at the start/end of the string.

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

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.