【问题标题】:How to Replace Words Outside Of Quotes如何替换引号之外的单词
【发布时间】:2015-02-27 18:02:36
【问题描述】:

我想在 Java 中使用 str.replaceAll 替换引号之外的字符串,但不改变引号内的单词

如果我用 Pie 代替 Apple:

输入:Apple "Apple Apple Apple"
期望的输出:派“Apple Apple Apple”

请注意引号内的单词未触及

如何做到这一点?所有帮助赞赏!

【问题讨论】:

  • 为什么你的例子中有括号?引号周围总是有括号吗?
  • 不,引号不会总是有括号
  • @freakshow1217 所以您只想更改单词的第一次出现?
  • 所有出现的单词,如果可能的话
  • 这会有更复杂的例子吗,例如苹果“苹果和香蕉”,应该改成派“苹果和香蕉”?如果是这样,那么正则表达式将不起作用。

标签: java regex string


【解决方案1】:

使用前瞻搜索Apple,以确保它没有被引号包围:

(?=(([^"]*"){2})*[^"]*$)Apple

替换为:

Pie

RegEx Demo


更新:

基于下面的 cmets 你可以使用:

代码:

String str = "Apple \"Apple\"";
String repl = str.replaceAll("(?=(([^\"]*\"){2})*[^\"]*$)Apple", "Pie");
//=> Pie "Apple" "Another Apple Apple Apple" Pie

【讨论】:

  • 这会产生(可能需要)将“CrabApple”更改为“CrabPie”的副作用,不是吗?
  • 我有一个问题:我想要它,即使它没有触及报价,它也不会被替换:“Apple Apple Apple”结果 ->“Apple Pie Apple”跨度>
  • 嗯,这会使正则表达式在很大程度上复杂化,我会更新答案。
【解决方案2】:

我想这就是你想要的:

String str = "Apple \"Apple\"";
String replace = str.replaceAll("(?<!\")Apple(?!\")", "Pie");

这是工作:https://regex101.com/r/kP0oV1/2

【讨论】:

  • 我将如何使用它?
【解决方案3】:

这适用于您的测试:

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);
    }
}

我正在使用所谓的negative lookahead and a negative lookbehind。它会查找前面或后面没有“”的匹配项。这对您有用吗?

【讨论】:

    【解决方案4】:

    尝试将单词与后面的空格匹配。

    /苹果\s/

    然后用 Pie 替换,后面有相同的空格。

    【讨论】:

      【解决方案5】:

      如果您愿意,如果您正在寻找更迭代的解决方案,也可以选择不使用更复杂的正则表达式来执行此操作。您可以在" 上拆分并替换偶数索引,然后重建字符串。

          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);
      

      输出:

      "unique" unique unique "unique" "unique" "unique" "unique" unique "unique unique" unique unique "
      "unique" potato potato "unique" "unique" "unique" "unique" potato "unique unique" potato potato "
      

      【讨论】:

        猜你喜欢
        • 2012-06-11
        • 2020-07-11
        • 2019-01-07
        • 2011-03-06
        • 2018-11-18
        • 2018-11-19
        • 1970-01-01
        • 2017-11-03
        • 2011-01-26
        相关资源
        最近更新 更多