- 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
Role of Matcher.group() method in Java Regular Expressions
The method java.time.Matcher.group() is used to find the subsequence in the input sequence string that is a match to the required pattern. This method returns the subsequence that is matched by the previous match which can even be empty.
A program that demonstrates the method Matcher.group() in Java regular expressions is given as follows:
Example
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Demo { public static void main(String args[]) { Pattern p = Pattern.compile("\w\d"); Matcher m = p.matcher("This is gr8"); System.out.println("The input string is: This is gr8"); System.out.println("The Regex is: \w\d"); System.out.println(); if (m.find()) { System.out.println("Match: " + m.group()); } } }
Output
The input string is: This is gr8 The Regex is: \w\d Match: r8
Now let us understand the above program.
The subsequence “\w\d” is searched in the string sequence "This is gr8". The find() method is used to find if the subsequence is in the input sequence and the required result is printed using the group() method. A code snippet which demonstrates this is as follows:
Pattern p = Pattern.compile("\w\d"); Matcher m = p.matcher("This is gr8"); System.out.println("The input string is: This is gr8"); System.out.println("The Regex is: \w\d"); System.out.println(); if (m.find()) { System.out.println("Match: " + m.group()); }
Advertisements