We
can assign a name to capturing group and use it in the Regular
expression processing.
Naming
Conventions
1.
The first character must be a letter.
2.
You can use uppercase letters 'A' through 'Z', lowercase letters 'a'
through 'z' and digits '0' through '9'.
The
newly added RegEx constructs to support the named capturing group
are:
(1)
(?<NAME>X) to define a named group NAME"
(3)
<$<NAME> to reference to captured group in matcher's
replacement str
(4)
group(String NAME) to return the captured input subsequence by the
given "named group"
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
No comments:
Post a Comment