[英]What's wrong with this replacement code?
我需要將{word}替換為名為group:(?<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”
怎么了?
我認為您在替換中使用了太多\\
。 嘗試
p = p.replaceAll("\\{(\\w+)\\}", "(?<$1>\\\\\\w+)");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.