- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Back references in Java regular expressions
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)
Example
Back references allow repeating a capturing group using a number like \# where # is the group number. See the example below:
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Tester { public static void main(String[] args) { //2 followed by 2 five times String test = "222222"; String pattern = "(\d\d\d\d\d)"; Pattern r = Pattern.compile(pattern); Matcher m = r.matcher(test); if (m.find( )) { System.out.println("Matched!"); }else{ System.out.println("not matched!"); } //\1 as back reference to capturing group (\d) pattern = "(\d)\1{5}"; r = Pattern.compile(pattern); m = r.matcher(test); if (m.find( )) { System.out.println("Matched!"); }else{ System.out.println("not matched!"); } } }
- Related Articles
- How regular expression back references works in Python?
- Capturing groups and back references in Java Regex
- Regex capturing groups and back references in Java
- Java Regular Expressions Tutorial
- Greedy quantifiers Java Regular expressions in java.
- Regular Expressions syntax in Java Regex
- Regex quantifiers in Java Regular Expressions
- Matcher.pattern() method in Java Regular Expressions
- Pattern.matches() method in Java Regular Expressions
- PatternSyntaxException class in Java regular expressions
- Explain quantifiers in Java regular expressions
- Java regular expressions sample examples
- Possessive quantifiers Java Regular expressions
- Java Regular expressions Logical operators
- Reluctant quantifiers Java Regular expressions

Advertisements