How to extract numbers from a string
Short answer
A Pattern describes what to look for, and results() returns a stream of all matches:
void main() {
String text = "Order 15 contains 3 items for 120 euros";
List<Integer> numbers = Pattern.compile("\\d+").matcher(text).results()
.map(match -> Integer.parseInt(match.group()))
.toList();
IO.println(numbers);
}Output:
[15, 3, 120]With a find() loop
The classic way is to call find() until there are no more matches:
void main() {
Matcher matcher = Pattern.compile("\\d+").matcher("a1b22c333");
while (matcher.find()) {
IO.println(matcher.group() + " at " + matcher.start());
}
}Output:
1 at 1
22 at 3
333 at 6Decimals and negatives
Extend the pattern with an optional minus sign and a fractional part:
void main() {
String text = "t = -3.5, then 12 and 0.75";
var numbers = Pattern.compile("-?\\d+(\\.\\d+)?").matcher(text).results()
.map(match -> Double.parseDouble(match.group()))
.toList();
IO.println(numbers);
}Output:
[-3.5, 12.0, 0.75]Just the digits
If you need all digits as one string, remove everything else:
void main() {
IO.println("+1 (555) 010-99".replaceAll("\\D", ""));
}Output:
155501099Common mistake
Calling group() without a successful find(). The matcher has not found a match yet and throws:
void main() {
Matcher matcher = Pattern.compile("\\d+").matcher("abc 42");
IO.println(matcher.group());
}Output:
Exception in thread "main" java.lang.IllegalStateException: No match foundFunctions used in this recipe
- Pattern.compile() — Compiles a regular expression into a Pattern object that can be reused many times.
- Matcher.find() — Searches for the next match of the pattern anywhere in the string.
- String.replaceAll() — Replaces every match of a regular expression.
- Integer.parseInt() — Converts a string containing an integer to an int.