Saturday, 1 November 2014

Backreferences

Capturing groups can remember text matched by the expression they enclose. Backreferencing is a feature that use the remembering capacity of Capturing groups.

Capturing Group
Description
\n
Matches with whatever the nth capturing group matched.
\k<name>
Matches with whatever the named-capturing group "name"matched.

For Example, regular expression '(\d{4}) \1' match the 4 digits which are repeating twice.

Enter Regular Expression
(\d{4}) \1
Enter the string
1234 1234
I found the text 1234 1234 starting at index 0 Ending at index 9

Enter the string
1234 5678 5678 1234
I found the text 5678 5678 starting at index 5 Ending at index 14

Another Example, regular expression '([a-z,A-Z]*) \1' match if same striing repeated twice.

Enter Regular Expression
([a-z,A-Z]*) \1
Enter the string
hari hari
I found the text hari hari starting at index 0 Ending at index 9

Enter the string
krishna krishna
I found the text krishna krishna starting at index 0 Ending at index 15

Enter the string
my name name is krishna
I found the text starting at index 2 Ending at index 3
I found the text name name starting at index 3 Ending at index 12
I found the text starting at index 12 Ending at index 13
I found the text starting at index 15 Ending at index 16


Enter Regular Expression
(a((b){2})) \2
Enter the string
abb bb
I found the text abb bb starting at index 0 Ending at index 6

Example 1 : Backreferencing using naming
import java.util.regex.*;
        
public class CaptureGroupEx {
    public static void main(String args[]){
        String name = "(?<number>\\d+)\\s\\k<number>";
        Matcher m = Pattern.compile(name).matcher("1234 1234");
        
        while (m.find()) {
            System.out.print("I found the text " + m.group());
            System.out.print(" starting at index " + m.start());
            System.out.println(" Ending at index " + m.end());
        }        
    }
}

Output

I found the text 1234 1234 starting at index 0 Ending at index 9




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment