- 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
Working with simple groups in Java Regular Expressions
Multiple characters can be treated as a single unit using groups 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.
A program that demonstrates groups 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("I am f9"); System.out.println("The input string is: I am f9"); System.out.println("The Regex is: \w\d"); System.out.println(); if (m.find()) { System.out.println("Match: " + m.group()); } } }
The output of the above program is as follows −
The input string is: I am f9 The Regex is: \w\d Match: f9
Now let us understand the above program.
The subsequence “\w\d” is searched in the string sequence "I am f9". 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("I am f9"); System.out.println("The input string is: I am f9"); System.out.println("The Regex is: \w\d"); System.out.println(); if (m.find()) { System.out.println("Match: " + m.group()); }
- Related Articles
- Working with Matcher.start() method in Java Regular Expressions
- Working with Matcher.end() method in Java Regular Expressions
- Non capturing groups Java regular expressions:
- Named captured groups Java regular expressions
- Named capture groups JavaScript Regular Expressions
- Validate Phone with Java Regular Expressions
- What is the groups() method in regular expressions in Python?
- Search and Replace with Java regular expressions
- Java Regular Expressions Tutorial
- Validate city and state with Java Regular Expressions
- Validate the ZIP code with Java Regular expressions
- Greedy quantifiers Java Regular expressions in java.
- Back references in Java regular expressions
- Regular Expressions syntax in Java Regex
- Regex quantifiers in Java Regular Expressions

Advertisements