1

我需要将 {word} 替换为名为组的正则表达式: (?< word >\w++) 以将来匹配表达式,即:/{name}/{age}... 此代码不起作用!

String p = "/{name}/{id}";
p = p.replaceAll("\\{(\\w+)\\}", "(?<$1>\\\\\\\\w+)");
Pattern URL_PATTERN = Pattern.compile(p);
CharSequence cs = "/lucas/3";
Matcher m = URL_PATTERN.matcher(cs);
if(m.matches()){
    for(int i=1;i<m.groupCount();++i){
        System.out.println(m.group("name"));
    }
}

结果:没有:(

但是当我得到替换的结果时: /(?\w+)/(?\w+) 并放入 Pattern.compile() 这有效:

String p = "/{name}/{id}";
p = p.replaceAll("\\{(\\w+)\\}", "(?<$1>\\\\\\\\w+)");
Pattern URL_PATTERN = Pattern.compile("/(?<name>\\w+)/(?<id>\\w+)");
System.out.println(p);
CharSequence cs = "/lucas/3";
Matcher m = URL_PATTERN.matcher(cs);
if(m.matches()){
    for(int i=1;i<m.groupCount();++i){
        System.out.println(m.group("name"));
    }
}

结果:“卢卡斯”

怎么了?

4

1 回答 1

1

我认为您在替换中使用了太多\。尝试

p = p.replaceAll("\\{(\\w+)\\}", "(?<$1>\\\\\\w+)"); 
于 2012-08-04T14:06:44.223 回答