Extract Digits from a String in Java

Hey Everyone! In this article, we will learn how to Extract Digits from a user-entered String in Java and then display each digit.

I hope this post is going to be interesting and you will enjoy it.


There are two ways to extract digits from a String. Let us see them one by one with example in Java code.

Extract digits from the String using Java isDigit() method.

The isDigit() method belongs to the Character Class in Java. If the character is a Decimal then it is considered as a Digit by the isDigit() method. Let us see the code now.

package program;

import java.util.Scanner;

  

public class Program {

   
    public static void main(String[] args) {
        
        Scanner sc = new Scanner(System.in);
        
        //Extract digits from a String
        
        System.out.println("Enter a String");
        //prompting the user to enter a String
        String str = new String();
        str=sc.nextLine();
        
        System.out.println("The Entered String is "+str);
        
        for (char dig : str.toCharArray())
        {
            
            if (Character.isDigit(dig)) 
            {
                System.out.println("The digit found is "+dig);
            }
        }
    }
    
}

The output will be:

run:
Enter a String
hel8lo th4er3
The Entered String is hel8lo th4er3
The digit found is 8
The digit found is 4
The digit found is 3
BUILD SUCCESSFUL (total time: 13 seconds)

Extracting Digits from a String using Regular Expressions

We can use Pattern and Matcher classes of java.util.regex; package of Java to use regular expressions to extract a digit from a String.

package program;

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;



  

public class Program {

   
    public static void main(String[] args) 
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a String ");
        String inp = new String();
        inp = sc.nextLine();
        Pattern p = Pattern.compile("\\d+");
        Matcher m = p.matcher(inp);
        while(m.find()) 
        {
            System.out.println("The digits extracted "+m.group()+" ");
            System.out.print(" ");
        }
    }
    
}

The output of the above program is given below:

Enter a String 
he4ll2o9
The digits extracted 4 
The digits extracted 2 
The digits extracted 9

Also, read:

We can clearly see that, we have successfully able to get all our digits from our given string. So we did our task successfully. You can also run both the methods in your own machine to see the result.

I hope this article was useful to you. If any doubts/suggestions leave a comment down below.

Leave a Reply

Your email address will not be published. Required fields are marked *