Java 如何替换引号外的单词
我想在Java中使用str.replaceAll替换引号外的字符串,但保留引号内的单词不变 如果我用派代替苹果: 输入:苹果“苹果”Java 如何替换引号外的单词,java,regex,string,Java,Regex,String,我想在Java中使用str.replaceAll替换引号外的字符串,但保留引号内的单词不变 如果我用派代替苹果: 输入:苹果“苹果” 期望输出:派“苹果” 请注意,引号内的单词未被触及 如何做到这一点?感谢大家的帮助 我想这就是你想要的: String str = "Apple \"Apple\""; String replace = str.replaceAll("(?<!\")Apple(?!\")", "Pie"); String str=“苹果\”苹果\”; String rep
期望输出:派“苹果” 请注意,引号内的单词未被触及
如何做到这一点?感谢大家的帮助 我想这就是你想要的:
String str = "Apple \"Apple\"";
String replace = str.replaceAll("(?<!\")Apple(?!\")", "Pie");
String str=“苹果\”苹果\”;
String replace=str.replaceAll(“(?这适用于您的测试:
package mavensandbox;
import static junit.framework.TestCase.assertEquals;
public class Test {
@org.junit.Test
public void testName() throws Exception {
String input = "Apple(\"Apple\")";
String output = replaceThoseWithoutQuotes("Apple", "Pie", input);
assertEquals("Pie(\"Apple\")", output);
}
private String replaceThoseWithoutQuotes(String replace, String with, String input) {
return input.replaceAll("(?<!\")" + replace + "(?!\")", with);
}
}
包mavensandbox;
导入静态junit.framework.TestCase.assertEquals;
公开课考试{
@org.junit.Test
public void testName()引发异常{
字符串输入=“苹果”(\“苹果\”);
字符串输出=不带引号的替换(“苹果”,“饼”,输入);
assertEquals(“Pie(\“Apple\”),输出;
}
私有字符串替换不带引号的字符串(字符串替换、字符串替换、字符串输入){
返回input.replaceAll((?使用lookaheads搜索Apple
,以确保它没有被引号包围:
(?=(([^"]*"){2})*[^"]*$)Apple
并替换为:
Pie
更新:
String str = "Apple \"Apple\"";
String repl = str.replaceAll("(?=(([^\"]*\"){2})*[^\"]*$)Apple", "Pie");
//=> Pie "Apple" "Another Apple Apple Apple" Pie
根据以下评论,您可以使用:
代码:
String str = "Apple \"Apple\"";
String repl = str.replaceAll("(?=(([^\"]*\"){2})*[^\"]*$)Apple", "Pie");
//=> Pie "Apple" "Another Apple Apple Apple" Pie
尝试将单词与后面的空格匹配
/苹果/
然后替换为后面有相同空格的饼图。如果您想寻找一个更迭代的解决方案,也可以选择不使用更复杂的正则表达式。您可以在“
上拆分,替换偶数索引,然后重新生成字符串
String input = "\"unique\" unique unique \"unique\" \"unique\" \"unique\" \"unique\" unique \"unique unique\" unique unique \"";
System.out.println(input);
String[] split = input.split("\"");
for (int i = 0; i < split.length; i = i + 2) {
split[i] = split[i].replaceAll("unique", "potato");
}
String output = "";
for (String s : split) {
output += s + "\"";
}
System.out.println(output);
为什么在你的例子中有paren?引号周围总是有paren吗?不,不总是有parenthensquotes@freakshow1217那么您只想更改单词的第一次出现?如果可能的话,所有出现的单词都会有更复杂的示例,例如Apple“Apple and Banana”“,哪个应该改成馅饼“苹果和香蕉”?如果是这样,那么regex将不起作用。我将如何使用它?这将产生(可能是期望的)副作用,将“Crappie”改为“Crappie”,不是吗?我有一个问题:我想要它,这样即使它不涉及报价,也不会被替换:“Apple”结果->“苹果派苹果”嗯,这将使正则表达式在很大程度上复杂化,我将更新答案。