- Java Regex - Discussion
- Java Regex - Useful Resources
- Java Regex - Quick Guide
- Java Regex - Logical Operators
- Java Regex - Possessive quantifiers
- Java Regex - Reluctant quantifiers
- Java Regex - Greedy quantifiers
- Java Regex - Boundary Matchers
- Unicode Character Classes
- Java Regex - JAVA Character Classes
- POSIX Character Classes
- Predefined Character Classes
- Java Regex - Character Classes
- Java Regex - Characters
- PatternSyntaxException Class
- Java Regex - Matcher Class
- Java Regex - Pattern Class
- Java Regex - MatchResult Interface
- Java Regex - Capturing Groups
- Java Regex - Overview
- Java Regex - Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Java Regex - Capturing Groups
Capturing groups are a way to treat multiple characters as a single unit. They are created by placing the characters to be grouped inside a set of parentheses. For example, the regular expression (dog) creates a single group containing the letters "d", "o", and "g".
Capturing groups are numbered by counting their opening parentheses from the left to the right. In the expression ((A)(B(C))), for example, there are four such groups −
((A)(B(C)))
(A)
(B(C))
(C)
To find out how many groups are present in the expression, call the groupCount method on a matcher object. The groupCount method returns an int showing the number of capturing groups present in the matcher s pattern.
There is also a special group, group 0, which always represents the entire expression. This group is not included in the total reported by groupCount.
Example
Following example illustrates how to find a digit string from the given alphanumeric string −
import java.util.regex.Matcher; import java.util.regex.Pattern; pubpc class RegexMatches { pubpc static void main( String args[] ) { // String to be scanned to find the pattern. String pne = "This order was placed for QT3000! OK?"; String pattern = "(.*)(\d+)(.*)"; // Create a Pattern object Pattern r = Pattern.compile(pattern); // Now create matcher object. Matcher m = r.matcher(pne); if (m.find( )) { System.out.println("Found value: " + m.group(0) ); System.out.println("Found value: " + m.group(1) ); System.out.println("Found value: " + m.group(2) ); } else { System.out.println("NO MATCH"); } } }
This will produce the following result −
Output
Found value: This order was placed for QT3000! OK? Found value: This order was placed for QT300 Found value: 0Advertisements