[英]Replace regex occurrences
I have an input string: 我有一个输入字符串:
"hello [you], this is [me]"
I have a function which maps a string to a string (hardcoded for the sake of simplicity): 我有一个将字符串映射到字符串的函数(为简单起见,采用硬编码):
public String map(final String input) {
if ("you".equals(input)) {
return "SO";
} else if ("me".equals(input)) {
return "Kate";
}
...
}
What is the most convenient way to replace each [(.*)?]
occurrence by its respective mapping (given by calling the map
function)? 用各自的映射(通过调用
map
函数给定[(.*)?]
替换每个[(.*)?]
出现的最方便的方法是什么?
If I am correct, you cannot use String.replaceAll()
here, since we don't know the replacement in advance. 如果我是正确的,您不能在这里使用
String.replaceAll()
,因为我们事先不知道替换方法。
First, the expression that you have is greedy. 首先,您拥有的表情是贪婪的。 A proper expression to match a token in square brackets is
\\[([^\\]]*)\\]
(backslashes need to be doubled for Java), because it avoids going past the closing square bracket * . \\[([^\\]]*)\\]
是与括号中的标记匹配的合适表达式(对于Java,反斜杠需要加倍),因为它可以避免使用右方括号* 。 I added a capturing group to access the content inside square brackets as group(1)
. 我添加了一个捕获组以将方括号内的内容作为
group(1)
。
Here is a way to do what you need: 这是一种满足您需求的方法:
Pattern p = Pattern.compile("\\[([^\\]]*)\\]");
Matcher m = p.matcher(input);
StringBuffer bufStr = new StringBuffer();
boolean flag = false;
while ((flag = m.find())) {
String toReplace = m.group(1);
m.appendReplacement(bufStr, map(toReplace));
}
m.appendTail(bufStr);
String result = bufStr.toString();
* You can use [.*?]
, too, but this reluctant expression may cause backtracking. *您也可以使用
[.*?]
,但是这种勉强的表达可能会导致回溯。
You can do something like: 您可以执行以下操作:
String line = "hello [you], this is [me]";
Pattern p = Pattern.compile("\\[(.*?)\\]");
Matcher m = p.matcher(line);
while (m.find()) {
// m.group(1) contains the text inside []
// line.replace(m.group(1), yourMap.get(m.group(1)));
// use StringBuilder to build the new string
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.