Find all numbers in the String [closed]

Use replaceAll:

String str = "qwerty1qwerty2";      
str = str.replaceAll("[^0-9]+", " ");
System.out.println(Arrays.asList(str.trim().split(" ")));

Output:

[1, 2]

[EDIT]

If you want to include - a.e minus, add -?:

String str = "qwerty-1qwerty-2 455 f0gfg 4";      
str = str.replaceAll("[^-?0-9]+", " "); 
System.out.println(Arrays.asList(str.trim().split(" ")));

Output:

[-1, -2, 455, 0, 4]

Description

[^-?0-9]+
  • + Between one and unlimited times, as many times as possible, giving back as needed
  • -? One of the characters “-?”
  • 0-9 A character in the range between “0” and “9”

Leave a Comment