java

How to extract numbers from a string with regex in Java

In this tutorial, we are going to see how to extract numbers from a string with regex in Java. Regular Expressions or Regex is an API for defining patterns that can be used to find, manipulate, and edit a string in Java. Regex is widely used to define constraints. Regular expressions are provided under java.util package.
 

Example 1: Extract all numbers from a string
import java.util.regex.*;

public class Main 
{
    public static void main(String[]args) 
    {
        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher("str54776str917str78001str");
		
        while(matcher.find()) 
        {
            System.out.println(matcher.group());
        }
    }
}

Output:

54776
917
78001

 
[st_adsense]  

Example 2: Extract the Nth digit of a string

If you want to extract only certain numbers from a string, you can provide the index of the numbers to extract to the group() function.

For example, if we want to extract only the second number of the string “str54776str917str78001str”, which is 917, we can use the following code:

import java.util.regex.*;

public class Main 
{
  public static void main(String[] args) 
  {
     Pattern pattern = Pattern.compile("[^\\d]*[\\d]+[^\\d]+([\\d]+)");
     Matcher matcher = pattern.matcher("str54776str917str78001str");

     if (matcher.find()) 
     {
         // second matching number
         System.out.println(matcher.group(1)); 
     }
  }
}

Output:

917
[st_adsense] 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 *