【问题标题】:replace substring of matched regex替换匹配的正则表达式的子字符串
【发布时间】:2011-09-02 21:15:09
【问题描述】:

我获取一些 html 并进行一些字符串操作,然后得到一个类似的字符串

string sample = "\n    \n   2 \n      \n  \ndl. \n \n    \n flour\n\n     \n 4   \n    \n cups of    \n\nsugar\n"

我想查找所有成分行并删除空格和换行符

2 分升。面粉4杯糖

到目前为止,我的方法如下。

Pattern p = Pattern.compile("[\\d]+[\\s\\w\\.]+");
Matcher m = p.matcher(Result);

while(m.find()) {
  // This is where i need help to remove those pesky whitespaces
}

【问题讨论】:

    标签: java regex string removing-whitespace


    【解决方案1】:

    sample = sample.replaceAll("[\\n ]+", " ").trim();

    输出:

    2 dl. flour 4 cups of sugar

    开头没有空格,结尾也没有空格。

    它首先用一个空格替换所有空格和换行符,然后从 begging / end 中修剪掉多余的空格。

    【讨论】:

      【解决方案2】:

      以下代码应该适合您:

      String sample = "\n    \n   2 \n      \n  \ndl. \n \n    \n flour\n\n     \n 4   \n    \n cups of    \n\nsugar\n";
      Pattern p = Pattern.compile("(\\s+)");
      Matcher m = p.matcher(sample);
      sb = new StringBuffer();
      while(m.find())
          m.appendReplacement(sb, " ");
      m.appendTail(sb);
      System.out.println("Final: [" + sb.toString().trim() + ']');
      

      输出

      Final: [2 dl. flour 4 cups of sugar]
      

      【讨论】:

      • 你的解决方案正是我所追求的,我明天试试。顺便说一句,\n 包含在 \s 中,因此您的模式中只需要 [\\s]+
      • 为什么不像其他人那样使用replaceAll()
      • 是的也可以使用replaceAll(),但 OP 试图使用 Pattern/Matcher 类来实现,所以使用它编写了代码。
      • 实际上,我使用模式/匹配器的原因是因为字符串还包含其他内容,但这就是实际的配方。我只是想格式化成分,以便它们可以显示在一个漂亮的列表中。
      【解决方案3】:

      我认为这样的事情对你有用:

      String test = "\n    \n   2 \n      \n  \ndl. \n \n    \n flour\n\n     \n 4   \n    \n cups of    \n\nsugar\n";
      
      /* convert all sequences of whitespace into a single space, and trim the ends */
      test = test.replaceAll("\\s+", " ");
      

      【讨论】:

        【解决方案4】:

        我假设\n 不是实际的换行符,但它也适用于linefeeds。 这应该可以正常工作:

        test=test.replaceAll ("(?:\\s|\\\n)+"," ");

        如果没有textual \n,它可以更简单:

        test=test.replaceAll ("\\s+"," ");

        您需要修剪前导/尾随空格。

        我使用 RegexBuddy 工具检查任何单个正则表达式,在这么多语言中非常方便。

        【讨论】:

        • 要匹配文字序列 \n(反斜杠 + 'n'),您需要在正则表达式 (\\\\n) 中使用 四个 反斜杠,而不是三个。但很明显 OP 确实在尝试匹配换行符。
        【解决方案5】:

        您应该能够使用标准的String.replaceAll(String, String)。第一个参数将采用您的模式,第二个参数将采用空字符串。

        【讨论】:

        • 这就是我需要正则表达式变量的地方,我真的不知道如何使用。让我举例说明:我的模式匹配“\n \n 2 \n \n \ndl。\n \n \n面粉\n\n \n”,我想用“2 dl。面粉”替换它。我的问题是如何从匹配的子字符串中提取信息?
        • @Flexo,看看我的回复,确实是这样。
        【解决方案6】:
        s/^\s+//s
        s/\s+$//s
        s/(\s+)/ /s
        

        运行这三个替换(将前导空格替换为空,将尾随空格替换为空,将多个空格替换为空格。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-11-30
          • 1970-01-01
          • 2012-01-25
          • 2019-10-23
          • 2013-01-23
          • 1970-01-01
          • 2017-01-23
          • 1970-01-01
          相关资源
          最近更新 更多