Named grouping in Java
The java.regex package in Java does not support named grouping. Java 7 and higher
Java 7 and higher now supports named grouping. Named groups can be defined using:
Named groups can be referenced using:
<code class="java">(?<name>capturing text)</code>
k
For versions prior to Java 7, the following alternatives are available:
Google named-regexYou can also support named grouping by writing your own version of Regex. For example, the Regex2 library provides this support.
Example
Example of regular expression using named grouping:
Example of Java code using named grouping:
(?<login>\w+) (?<id>\d+)
Example of using named grouping to replace text:
Pattern pattern = Pattern.compile("(?<login>\w+) (?<id>\d+)");
Matcher matcher = pattern.matcher("TEST 123");
if (matcher.find()) {
String login = matcher.group("login");
String id = matcher.group("id");
}
Example of using named grouping backreference:
<code class="java">String result = matcher.replaceAll("aaaaa__sssss_____");</code>
The above is the detailed content of How can I use named capturing groups in Java regular expressions?. For more information, please follow other related articles on the PHP Chinese website!