正则表达式 string.replaceAll替换花括号 报错illegal repetition near index 0

 1 String regex = "(\\$|\\#)\\{[^{}]*\\}";//匹配的是#{xxx}或者${xxx}
 2 List<WatcherTaskAgentFileMapping> watcherTaskAgentFileMappingList = agentFileQueryDao.queryWatcherAgentFileList(taskId);
 3 Map<String, String> paramMap = new HashMap<>();
 4 for (WatcherTaskAgentFileMapping watcherTaskAgentFileMapping : watcherTaskAgentFileMappingList) {
 5     Integer count = 1;
 6     String fileUrl = watcherTaskAgentFileMapping.getFileUrl();
 7     Pattern p = Pattern.compile(regex);
 8     Matcher matcher = p.matcher(fileUrl);
 9     while (matcher.find()) {
10         String searchStr = fileUrl.substring(matcher.start(), matcher.end());
11         if (StringUtils.isEmpty(paramMap.get(searchStr))) {
12             paramMap.put(searchStr, "${参数" + count++ + "}");
13         }
14     }
15 }
16 if (!CollectionUtils.isEmpty(paramMap)) {
17     String regexAll = "(\\$|\\#)\\{[^{参数}]*\\}";//匹配除$/#{参数x} 外的 $/#{xxx}
18     Pattern p = Pattern.compile(regexAll);
19     for (WatcherTaskAgentFileMapping watcherTaskAgentFileMapping : watcherTaskAgentFileMappingList) {
20         for (String paramKey : paramMap.keySet()) {
21             String fileUrl = watcherTaskAgentFileMapping.getFileUrl();
22             while (p.matcher(fileUrl).find()) {//因为string.replaceAll(a,b) a 参数,可以单独替换‘{’或者‘}’,如果是字符串{xxx},会报错,但是replace就不会
23                 fileUrl = watcherTaskAgentFileMapping.getFileUrl().replace(paramKey, paramMap.get(paramKey));
24             }
25             watcherTaskAgentFileMapping.setFileUrl(fileUrl);
26         }
27     }
28 }

 replaceAll 替换带有花括号的字符串会报错,单独替换前花括号或者后花括号加上转义符不会报错;例如 "{cesi".replaceAll("\\{","a") = acesi

 replace 替换带有花括号的字符串不会报错

posted @ 2022-11-11 14:55  酷盖的小机灵  阅读(1472)  评论(0编辑  收藏  举报