regex get amount of numbers in string code example
Example 1: regex match any number of digits
For matching an integer number of one single char/digit, specify:
[0-9]
But for matching any number of more than one char/digit; add "+":
[0-9]+
Example for matching hour with minutes of HH:MM format in a file:
grep "[0-9]\+\:[0-9]\+" file.txt
Example 2: regex to get all numbers in a string
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Just {
public static void main(String[] args) {
String data = "abc12def334hjdsk7438dbds3y388";
//Regular expression to digits
String regex = "([0-9]+)";
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Creating a Matcher object
Matcher matcher = pattern.matcher(data);
System.out.println("Digits in the given string are: ");
while(matcher.find()) {
System.out.print(matcher.group()+" ");
}
}
}