Find All Digits in String

This program finds all digits in a string using regex.

Problem Statement

Write a Java program to find all digits in a given string.

Source Code

1 import java.util.regex.*;
2 public class RegexFindDigits {
3 public static void main(String[] args) {
4 System.out.println("Eduinq Regex Find Digits");
5 String str="Eduinq123Test456";
6 Pattern p=Pattern.compile("\\d+");
7 Matcher m=p.matcher(str);
8 while(m.find()){
9 System.out.println("Found digits: "+m.group());
10 }
11 }
12 }

Program Output

Eduinq Regex Find Digits
Found digits: 123
Found digits: 456

Explanation

A Pattern is compiled for the regex \d+, and the Matcher's find() method is called repeatedly in a loop to locate every group of consecutive digits in the string, demonstrating regex-based digit extraction.

Quick Links to Explore