【发布时间】:2014-04-16 03:38:02
【问题描述】:
在 java 中,我只想将匹配部分中的捕获组替换为其他值,而要替换的值取决于捕获组。
例如:
String str = "fname:hello hello:world ffff:off";
Map<String, String> mapping = new HashMap<String, String>();
dat.put("fname", "meme");
dat.put("hello", "below");
dat.put("ffff", "ssss");
Pattern pat = Pattern.compile("([a-zA-Z_]+):");
在上面的代码中,我想将模式“pat”的捕获组部分替换为“mapping”中找到的相应映射。 即替换后,“str”字符串应转换为“meme:hello below:world ssss:off” 我怎样才能做到这一点? 感谢您的帮助。
【问题讨论】:
-
每个地图术语将替换单词出现的任何位置。它可能适用于我的示例。所以一般来说,我想用一些取决于捕获组的值替换匹配部分的捕获组。