
- Java Tutorial
- Java - Home
- Java - Overview
- Java - Environment Setup
- Java - Basic Syntax
- Java - Object & Classes
- Java - Constructors
- Java - Basic Datatypes
- Java - Variable Types
- Java - Modifier Types
- Java - Basic Operators
- Java - Loop Control
- Java - Decision Making
- Java - Numbers
- Java - Characters
- Java - Strings
- Java - Arrays
- Java - Date & Time
- Java - Regular Expressions
- Java - Methods
- Java - Files and I/O
- Java - Exceptions
- Java - Inner classes
- Java Object Oriented
- Java - Inheritance
- Java - Overriding
- Java - Polymorphism
- Java - Abstraction
- Java - Encapsulation
- Java - Interfaces
- Java - Packages
- Java Advanced
- Java - Data Structures
- Java - Collections
- Java - Generics
- Java - Serialization
- Java - Networking
- Java - Sending Email
- Java - Multithreading
- Java - Applet Basics
- Java - Documentation
- Java Useful Resources
- Java - Questions and Answers
- Java - Quick Guide
- Java - Useful Resources
- Java - Discussion
- Java - Examples
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
- Related Articles
- Replacing all the matched contents Java regular expressions
- Looping over matches with JavaScript regular expressions
- How to find the subsequence in an input sequence that matches the pattern required in Java Regular Expressions?
- Use the ? quantifier in Java Regular Expressions
- Reset the Matcher in Java Regular Expressions
- Replace all words with another string with Java Regular Expressions
- Java Regular Expressions Tutorial
- Regular expression matches multiple lines in Java
- Validate the ZIP code with Java Regular expressions
- Explain the sub-expression "[...]" in Java Regular expressions
- Explain the Metacharacter "B" in Java Regular Expressions.
- Java program to find all close matches of input string from a list
- Java regular expressions sample examples
- Possessive quantifiers Java Regular expressions
- Java Regular expressions Logical operators

Advertisements