- Trending Categories
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
How to capture multiple matches in the same line in Java regex
Example
import java.util.regex.*; class PatternMatcher { public static void main(String args[]) { int count = 0; // String to be scanned to find the pattern. String content = "aaa bb aaa"; String string = "aaa"; // Create a Pattern object Pattern p = Pattern.compile(string); // get a matcher object Matcher m = p.matcher(content); while(m.find()) { count++; System.out.println("Match no:"+count); System.out.println("Found at: "+ m.start()+ " - " + m.end()); } } }
Output
Match no:1 Found at: 0 - 3 Match no:2 Found at: 7 - 10
Note
start() – This method used for getting the start index of a match that is being found using find() method.
end() –This method used for getting the end index of a match that is being found using find() method. It returns index of character next to last matching character.
- Related Articles
- Difference between matches() and find() in Java Regex
- Regular expression matches multiple lines in Java
- Regex - reusing patterns to capture groups in JavaScript?
- What is difference between matches() and find() in Java Regex?
- Regex to match lines containing multiple strings in Java
- C# Regex. Matches Method
- Swift Extract Regex Matches
- How to match a line not containing a word in Java Regex
- How to check multiple regex patterns against an input? Using Java.
- How to input multiple values from user in one line in Java?
- How to replace multiple spaces in a string using a single space using Java regex?
- How to capture divide by zero exception in Java?
- How to capture file not found exception in Java?
- How to write JavaScript Regular Expression for multiple matches?
- How to match end of a particular string/line using Java RegEx

Advertisements