gene b. gene b. - 3 months ago 17
Java Question

Java Regexp "\\d+" (Digits Only) not working

Input string:

07-000


JAVA Regexp:
\\d+
(digits only)

Expected Result:
07000
(digits only from input string)

Then why does this Java code return
07
only?

Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher("07-000");

String result = null;
if (matcher.find()) {
result = matcher.group();
}
System.out.println(result);

Answer

Then why does this Java code return 07 only?

It returns only 07 because that is the first group found by your regex, you need a while loop to get all groups and later you can concatenate them to get all numbers in one string.

Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher("07-000");
StringBuilder sb = new StringBuilder();
while (matcher.find()) 
{
     sb.append( matcher.group() );
}

System.out.println( "All the numbers are : " +  sb.toString() );