java

How to extract numbers from an alphanumeric string in Java

In this tutorial, we are going to see how to extract integers from a string in Java. Here is the steps:

  • Step 1: Replace all non-numeric characters with spaces.
  • Step 2: Replace each group of consecutive spaces with a single space.
  • Step 3: Remove leading and trailing spaces and just leave the numbers.

 

Java Program to extract numbers from an alphanumeric string:
public class Main { 
  
    static String getNbr(String str) 
    { 
        // Replace each non-numeric number with a space
        str = str.replaceAll("[^\\d]", " "); 
        // Remove leading and trailing spaces
        str = str.trim(); 
        // Replace consecutive spaces with a single space
        str = str.replaceAll(" +", " "); 
  
        return str; 
    } 
  
    public static void main(String[] args) 
    { 
        String str = "texte321 paragraphe12 569 lorem"; 
        System.out.print(getNbr(str)); 
    } 
}

Output:

321 12 569
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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