java正则表达式 组_Java中的正则表达式命名组

在Java 7的官方发行版中,支持命名捕获组的构造是:(?capturing text) 定义命名组“名称”

\k 反向引用命名组“名称”

${name} 在Matcher的替换字符串中引用捕获的组

Java 7之前的其他替代方案是:

(原始答案:2009年1月,现在已经破了下两个链接)

您不能引用命名组,除非您编写自己的Regex版本...

(有限的实现,正如tchrist再次指出的那样,因为它只查找ASCII标识符.tchrist将限制详述为:只能在每个相同的名称上有一个命名组(您不能总是控制它!)并且不能将它们用于正则表达式递归。

注意:您可以在Perl和PCRE正则表达式中找到真正的正则表达式递归示例,如Regexp Power,PCRE规范和带平衡括号的匹配字符串幻灯片中所述)

例:

串:"TEST 123"

正则表达式:"(?\\w+) (?\\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 '

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

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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值