【问题标题】:Use regex pattern matching to remove the two leading and trailing lines使用正则表达式模式匹配删除两个前导和尾随行
【发布时间】:2020-10-30 06:48:02
【问题描述】:

我的字符串如下所示,字符串由换行符连接。在这个字符串中,前两行和后两行是固定的,public class FakeClass {/n public void fakeMethod() {/n

    String sampleCode =
        String.format(
            createLines(7),
            "public class FakeClass {\n",
            "  public void fakeMethod() {\n",
            "    int a = 5;\n",
            "    int b = 6;\n",
            "    a = b;\n",
            "  }\n",
            "}\n");
        );

  private static String createLines(int numLines) {
    return new String(new char[numLines]).replace("\0", "%s");
  }

我想去掉两条前导线和两条尾随线。我可以简单地使用子字符串

String result = sampleCode.substring(53, sampleCode.length() - 5)

输出是:

assertEqual(result, String.format(
       createLine(3),
       "    int a = 5;\n",
       "    int b = 6;\n",
       "    a = b;\n",
       ));

我想知道我们是否可以使用正则表达式模式匹配来删除两条前导和尾随行。

【问题讨论】:

  • 能否添加预期的输出
  • 由\n分割得到一个单独的行数组,然后通过丢弃前2个元素来做一个子列表
  • 只添加预期的输出。
  • @anubhava 谢谢,但我正在寻找一种使用正则表达式的方法。由\n 分割,占用另一个空间。
  • @anubhava 只是添加功能,对不起。

标签: java regex


【解决方案1】:

您可以使用此正则表达式删除前 2 行和后 2 行:

String code = sampleCode.replaceAll("^([^\n]*\n){2}|([^\n]*\n){2}$", "");

RegEx Demo

  • ^([^\n]*\n){2} 匹配字符串的前 2 行
  • ([^\n]*\n){2}$ 匹配最后两行字符串

【讨论】:

    【解决方案2】:

    需要使用java.util.regex.Pattern来激活多行搜索:

    String sampleCode
            = String.format(
                    createLines(7),
                    "public class FakeClass {\n",
                    "  public void fakeMethod() {\n",
                    "    int a = 5;\n",
                    "    int b = 6;\n",
                    "    a = b;\n",
                    "  }\n",
                    "}\n");
    Pattern pattern = Pattern.compile("(?=.*[{}])(.*)",Pattern.MULTILINE);
    sampleCode = pattern.matcher(sampleCode).replaceAll("");
    pattern = Pattern.compile("^(.+)$",Pattern.MULTILINE);
    System.out.println(pattern.matcher(sampleCode).replaceAll("\"$1\\\\n\""));
    

    输出:

    "    int a = 5;\n"
    "    int b = 6;\n"
    "    a = b;\n"
    

    您可以使用 trim() 方法删除每个删除行中的 \n

    【讨论】:

    • 感谢分享。预期的结果应该保持缩进和换行。
    • 我还尝试String result = sampleCode.replace("public class FakeClass {\n", "") .replace(" public void fakeMethod() {\n", "") 删除第一行尾随行。但我没有算出最后两行,比如“}\\r?\\n}$”。
    • 我改变了它,它按预期工作,在第一个正则表达式中它删除了前两行,第二行中的最后两行带回 " \n"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-16
    • 1970-01-01
    • 1970-01-01
    • 2020-07-20
    相关资源
    最近更新 更多