about
named-regexp
backports named capture groups from Java 7 to Java 5/6
usage
named groups
To create a named capture group, use(?<name>...)
, as in:
Pattern p = Pattern.compile("abc(?<foo>\\d+)xyz");
Matcher m = p.matcher("abc123xyz");
System.out.println(m.find()); // true
System.out.println(m.group("foo")); // 123
back references
To back-reference a named group in a pattern, use\k<name>
, as in:
Pattern p = Pattern.compile("abc(?<foo>\\d+)def\\k<foo>");
Matcher m1 = p.matcher("abc123def123ghi");
Matcher m2 = p.matcher("abc123def456ghi");
System.out.println(m1.find()); // true
System.out.println(m1.group("foo")); // 123
System.out.println(m2.find()); // false
replacement references
To reference a named group for string replacement, use${name}
, as in:
Pattern p = Pattern.compile("abc(?<foo>\\d+)def");
Matcher m = p.matcher("abc123def");
System.out.println(m.replaceAll("${foo}456 ${foo}")); // 123456 123
download
Maven dependency:<dependency>
<groupId>com.github.tony19</groupId>
<artifactId>named-regexp</artifactId>
<version>1.0.0</version>
</dependency>
docs
Check out the javadocs