我正在尝试分析一些文本,我需要在字符串中交换两个子字符串,例如在下面的文本中我想交换“很高兴见到你”和“你好吗”
Hi nice to see you? I'm fine Nice! how are you some other text
所以结果应该是:
Hi how are you? I'm fine Nice! nice to see you some other text
首先,我编写了这个方法,并且可以正常使用这个简单的例子:
public static String Swap(String source, String str1, String str2) {
source=source.replace(str1, str2);
source=source.replaceFirst(str2, str1);
return source;
}
我需要将此方法用于更复杂的文本,如下所示,但由于replaceFirst使用正则表达式,因此无法使用我的方法进行交换。
f(f(x))*g(g(x))
我想交换f(x)和g(x),但它不会说话。
有没有其他方法可以做到这一点?
答案 0 :(得分:3)
试试这个:
source=source.replace(str1, str2);
// handle things like "f(f(x))*g(g(x))"
source=source.replaceFirst(Pattern.quote(str2), Matcher.quoteReplacement(str1));
请参阅Pattern.quote here的文档。
请参阅Matcher.quoteReplacement here的文档。
警告:强> 您选择的这种方法有两个很大的假设!
str2
必须出现在str1
之前的来源中,str2
必须只在源字符串中出现一次需要更多general solution来消除这些问题。
例如:
String longer = str1;
String shorter = str2;
if(str2.length() > str1.length()) {
longer = str2;
shorter = str1;
}
Pattern p = Pattern.compile(Pattern.quote(longer) + "|" + Pattern.quote(shorter));
Matcher m = p.matcher(source);
StringBuffer sb = new StringBuffer();
while (m.find()) {
String replacement = str1;
if(m.group(0).equals(str1)) {
replacement = str2;
}
m.appendReplacement(sb, Matcher.quoteReplacement(replacement));
}
m.appendTail(sb);
System.out.println(sb.toString());