Many regular engines support named groupings, and Java is introduced in Java7, syntax and. NET similar (. NET allows the same expression to appear with the same name as the same group, Java is not allowed).
A named grouping is a good idea to name a group. Here's a quick example of how to use Java and considerations.
1. Define a group named name in regular
(? <name>x)
Here x for us to match the content, note that in this name can not be repeated, the name can not begin with the number!
2. Reverse reference to what the name group matches
\k<name>
Note that the reverse reference is what the group matches, not the group's expression.
3. In substitution, reference to the string captured in group name
${name}
4. Gets the string that the name group captures
Group (String NAME)
Note: You can also use ordinal to reference named captures, with ordinal numbers starting at 1, and 0 as the full matching result of a regular.
The following is a simple regular to obtain the month and year as an example:
String s = "2015-10-26";
Pattern p = pattern.compile ("(? <year>\\d{4})-(? <month>\\d{2})-(? <day>\\d{2})");
Matcher m = P.matcher (s);
if (M.find ()) {
System.out.println ("Year:" + M.group ("year")); Year
System.out.println ("Month:" + m.group ("month")); Month
System.out.println ("Day:" + m.group ("Day")); Day
System.out.println ("Year:" + m.group (1)); The first group of
System.out.println ("Month:" + m.group (2)); The second group of
System.out.println ("Day:" + m.group (3)); Group III
}
System.out.println (S.replaceall (? <year>\\d{4})-(? <month>\\d{2})-(? <day>\ \D{2}) "," ${day}-${month}-${year} "); Change the year-month-day form to the day-month-year format
Output results
year:2015
month:10
day:26
year:2015
month:10
day:26
26-10-2015
The above is the entire content of this article, I hope to help you learn.