Many regular engines support named grouping. Java introduced this feature in java7. The syntax is similar to .Net (.Net allows groupings with the same name to appear in the same expression, but Java does not).
Naming a group is easy to understand, it means naming the group. Below is a brief demonstration of how to use and precautions in Java.
1. Define a group named NAME in the regular
(?<NAME>X)
Here X is the content we want to match. Note that the name cannot be repeated in this, and the name cannot start with a number!
2. Backreferences to the content matched by the NAME group
/k<NAME>
Note that backreferences are for what the group matches, not for the group's expression.
3. In replacement, refer to the string captured in the group NAME
${NAME}
4. Get the string captured by the NAME group
group(String NAME)
Note: You can also use sequence numbers to reference named captures. The sequence numbers start from 1 and 0 is the complete matching result of the regular.
Here is a simple rule to obtain the year, month and day separately 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")); //Daily 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)); //The third group} System.out.println(s.replaceAll("(?<year>//d{4})-(?<month>//d{2})-(?<day>//d{2})", "${day}-${month}-${year}")); //Change the date of the year-month-day form to the day-month-year form Output result
year: 2015month: 10day: 26year: 2015month: 10day: 2626-10-2015
The above is all about this article, I hope it will be helpful to everyone's learning.