![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Getting the list of all the matches Java regular expressions
Java does not provide any method to retrieve the list of all matches we need to use Lists and add the results to it in the while loop.
Example
import java.util.ArrayList; import java.util.Iterator; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ListOfMatches{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter input text: "); String input = sc.nextLine(); String regex = "\d+"; //Creating a pattern object Pattern pattern = Pattern.compile(regex); ArrayList list = new ArrayList(); //Matching the compiled pattern in the String Matcher matcher = pattern.matcher(input); while (matcher.find()) { list.add(matcher.group()); } Iterator it = list.iterator(); System.out.println("List of matches: "); while(it.hasNext()){ System.out.println(it.next()); } } }
Output
Enter input text: sample 1432 text 53 with 363 numbers List of matches: 1432 53 363
Advertisements