Extract Numbers from Text

This program extracts numbers from text using regex.

Problem Statement

Write a Java program to extract numbers from "Order 123 shipped on 15th".

Source Code

1 import java.util.regex.*;
2 public class RegexExtractNumbers {
3 public static void main(String[] args) {
4 System.out.println("Eduinq Regex Extract Numbers");
5 String str="Order 123 shipped on 15th";
6 Pattern p=Pattern.compile("\\d+");
7 Matcher m=p.matcher(str);
8 while(m.find()) System.out.println("Extracted number: "+m.group());
9 }
10 }

Program Output

Eduinq Regex Extract Numbers
Extracted number: 123
Extracted number: 15

Explanation

The regex \d+ matches sequences of digits, and the Matcher's find() method is called repeatedly in a loop to extract every numeric group present in the text.

Quick Links to Explore