假如我的key不是abc,能帮我以+或-符号来进行匹配替换吗
时间: 2024-01-12 20:02:22 浏览: 26
当key不是固定的时候,你可以使用正则表达式中的"\\w+"来匹配任意单词字符,包括a、b、c等,或者使用"\\w{1}"来匹配任意一个单词字符。然后使用"+"或"-"符号进行匹配替换。
下面是一个示例代码:
```java
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceString {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("key1", 1);
map.put("key2", 2);
map.put("key3", 3);
String str = "key1 + key2 - key3";
Pattern pattern = Pattern.compile("\\w+");
Matcher matcher = pattern.matcher(str);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
String group = matcher.group();
if (map.containsKey(group)) {
int value = map.get(group);
matcher.appendReplacement(sb, String.valueOf(value));
}
}
matcher.appendTail(sb);
String result = sb.toString();
System.out.println(result);
}
}
```
输出结果为:1 + 2 - 3
希望这个答案对你有所帮助。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)