我需要用正则表达式组替换{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”
怎么了?
答案 0 :(得分:1)
我认为您在替换中使用了太多\
。尝试
p = p.replaceAll("\\{(\\w+)\\}", "(?<$1>\\\\\\w+)");