How to extract multiple integers from a String in Java?

Java 8Object Oriented ProgrammingProgramming

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]
raja
Published on 24-Apr-2019 08:55:25
Advertisements