asdffasdf
asdffasdf

Reputation: 53

How do I get the numbers out of a String?

So I am currently experimenting with Strings in a List and I want to parse the Integers out of the Strings.

`List <String> test = new LinkedList<>();
 test.add("Hello123")            //I want ["123"]
 test.add("123Hello456")         //I want ["123456"]
 test.add("123Hello 456")        //I want ["123, 456"]

But with that split function you do not get ["123456"] in line 3. You get ["123", "456"], which I do not want.

Does anybody have an idea how to solve this problem? Thanks in advance

Upvotes: 1

Views: 102

Answers (1)

Instead of x.split("\\D+"), do x.replaceAll("[^\\d\\s]", "").split("\\s+"). The replaceAll removes everything except the digits and whitespace, and the split splits on the whitespace.

Upvotes: 4

Related Questions