这个替换代码出了什么问题?

时间:2012-08-04 13:53:40

标签: java regex string replace

我需要用正则表达式组替换{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"));
    }
}

结果:“lucas”

怎么了?

1 个答案:

答案 0 :(得分:1)

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

p = p.replaceAll("\\{(\\w+)\\}", "(?<$1>\\\\\\w+)");