(更新:2011 年 8 月)
正如geofflane 在his answer 中提到的那样,Java 7 now support named groups。
tchrist 在评论中指出支持是有限的。
他在他的精彩回答“Java Regex Helper”中详细说明了局限性
September 2010 in Oracle's blog 中提供了 Java 7 正则表达式命名组支持。
在 Java 7 的正式版本中,支持命名捕获组的结构是:
-
(?<name>capturing text) 定义一个命名组“名称”
-
\k<name> 反向引用命名组“名称”
-
${name} 引用 Matcher 替换字符串中捕获的组
-
Matcher.group(String name) 返回给定“命名组”捕获的输入子序列。
Java 7 之前的其他替代方案是:
(原始答案:2009 年 1 月,接下来的两个链接现已断开)
您不能引用命名组,除非您编写自己的正则表达式版本...
这正是Gorbush2 did in this thread。
Regex2
(有限的实现,正如tchrist 再次指出的那样,因为它只查找 ASCII 标识符。tchrist 详细说明了限制:
每个同名只能有一个命名组(您并不总是可以控制它!)并且不能将它们用于正则表达式内递归。
注意:您可以在 Perl 和 PCRE 正则表达式中找到真正的正则表达式递归示例,如 Regexp Power、PCRE specs 和 Matching Strings with Balanced Parentheses 幻灯片中所述)
例子:
字符串:
"TEST 123"
正则表达式:
"(?<login>\\w+) (?<id>\\d+)"
访问
matcher.group(1) ==> TEST
matcher.group("login") ==> TEST
matcher.name(1) ==> login
替换
matcher.replaceAll("aaaaa_$1_sssss_$2____") ==> aaaaa_TEST_sssss_123____
matcher.replaceAll("aaaaa_${login}_sssss_${id}____") ==> aaaaa_TEST_sssss_123____
(从实现中提取)
public final class Pattern
implements java.io.Serializable
{
[...]
/**
* Parses a group and returns the head node of a set of nodes that process
* the group. Sometimes a double return system is used where the tail is
* returned in root.
*/
private Node group0() {
boolean capturingGroup = false;
Node head = null;
Node tail = null;
int save = flags;
root = null;
int ch = next();
if (ch == '?') {
ch = skip();
switch (ch) {
case '<': // (?<xxx) look behind or group name
ch = read();
int start = cursor;
[...]
// test forGroupName
int startChar = ch;
while(ASCII.isWord(ch) && ch != '>') ch=read();
if(ch == '>'){
// valid group name
int len = cursor-start;
int[] newtemp = new int[2*(len) + 2];
//System.arraycopy(temp, start, newtemp, 0, len);
StringBuilder name = new StringBuilder();
for(int i = start; i< cursor; i++){
name.append((char)temp[i-1]);
}
// create Named group
head = createGroup(false);
((GroupTail)root).name = name.toString();
capturingGroup = true;
tail = root;
head.next = expr(tail);
break;
}