如何用Java中的不同值替换字符串中多次出现的相同正则表达式模式



考虑如下示例:

String String = "嗨$?你好$?"字符串对象中的"$?"是正则表达式模式。第一次出现$?必须用"there"代替;第二次出现$?必须替换为"world"

如何使用Java实现相同的?或者在Apache commons StringUtils中是否有任何方法可以实现相同的功能?

下面是使用正式Java模式匹配器的一般方法。我们可以将替换的字符串项存储在一个列表中,然后在$上迭代输入字符串匹配。对于每个匹配项,我们可以用一个替换项替换。

String string = "Hi$?Hello$?";
StringBuffer sb = new StringBuffer();
List<String> replacements = Arrays.asList(new String[] {"there", "world"});
Pattern r = Pattern.compile("\$");
Matcher m = r.matcher(string);
int counter = 0;
while (m.find()) {
m.appendReplacement(sb, replacements.get(counter++));
}
m.appendTail(sb);
System.out.println(sb.toString());  // Hithere?Helloworld?

如果您需要的是顺序替换一些占位符字符串在搜索字符串,您可以使用Apache StringUtils:

String string = "Hi$?Hello$?";
String placeHolder = "$?";
String[] replacements = {"there", "world"};
for (String replacement : replacements) {
string = StringUtils.replaceOnce(string, placeHolder, replacement);
}
System.out.println(string);

,前提是事先知道序列,并且保证存在占位符。

我认为您不应该关注某些replaceString方法,因为在每次迭代中您都会收到一个新字符串。这是没有效率的。

为什么不用StringBuilder呢?

public static String replaceRegexp(String str, String placeHolder, String... words) {
int expectedLength = str.length() - placeHolder.length() * words.length + Arrays.stream(words).mapToInt(String::length).sum();
StringBuilder buf = new StringBuilder(expectedLength);
int prv = 0;
int i = 0;
int pos;
while ((pos = str.indexOf(placeHolder, prv)) != -1 && i < words.length) {
buf.append(str.substring(prv, pos));
buf.append(words[i++]);
prv = pos + placeHolder.length();
}
return buf.append(str.substring(prv)).toString();
}

我推荐第三种解决方案。

试试这个。

public static void main(String[] args) {
String string = "Hi$?Hello$?";
String[] rep = {"there", "world"};
String output = string.replaceFirst(
"\$\?(.*)\$\?", rep[0] + "$1" + rep[1]);
System.out.println(output);
}
输出:

HithereHelloworld

static final Pattern PAT = Pattern.compile("\$\?");
public static void main(String[] args) {
String string = "Hi$?Hello$?";
String[] rep = {"there", "world"};
int[] i = {0};
String output = PAT.matcher(string).replaceAll(m -> rep[i[0]++]);
System.out.println(output);
}

static final Pattern PAT = Pattern.compile("\$\?");
public static void main(String[] args) {
String string = "Hi$?Hello$?";
List<String> rep = List.of("there", "world");
Iterator<String> iter = rep.iterator();
String output = PAT.matcher(string).replaceAll(m -> iter.next());
System.out.println(output);
}

最新更新