Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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]
Advertisements