How to extract multiple integers from a String in Java?


Let’s say the following is our string with integer and characters −

String str = "(29, 12; 29, ) (45, 67; 78, 80)";

Now, to extract integers, we will be using the following pattern −

\d

We have set it with Pattern class −

Matcher matcher = Pattern.compile("\d+").matcher(str);

Example

 Live Demo

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo {
   public static void main(String[] args) {
      String str = "(29, 12; 29, ) (45, 67; 78, 80)";
      Matcher matcher = Pattern.compile("\d+").matcher(str);
      List<Integer>list = new ArrayList<Integer>();
      while(matcher.find()) {
         list.add(Integer.parseInt(matcher.group()));
      }
      System.out.println("Integers = "+list);
   }
}

Output

Integers = [29, 12, 29, 45, 67, 78, 80]

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

437 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements