首页 > 其他分享 >正则表达式 string.replaceAll替换花括号 报错illegal repetition near index 0

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

时间:2022-11-11 15:01:18浏览次数:54  
标签:index string matcher 报错 paramMap watcherTaskAgentFileMapping fileUrl String

 1 String regex = "(\\$|\\#)\\{[^{}]*\\}";
 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 = "(\\$|\\#)\\{[^{参数}]*\\}";
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 替换带有花括号的字符串会报错,单独替换前花括号或者后花括号不会报错;

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

标签:index,string,matcher,报错,paramMap,watcherTaskAgentFileMapping,fileUrl,String
From: https://www.cnblogs.com/yxl-wyb/p/16880477.html

相关文章