有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用正则表达式在双线中断前删除字符串

我有这样一根绳子:

this is my text
more text
more text

text I want
is below

我只想要双线分隔符下面的文本,而不是之前的内容

以下是我认为有效的方法:

myString.replaceFirst(".+?(\n\n)","");

然而,它不起作用。任何帮助都将不胜感激


共 (3) 个答案

  1. # 1 楼答案

    为什么不:

    s = s.substring(s.indexOf("\n\n") + 2);

    请注意,它可能是+1、+2或+3。我现在不想打开电脑测试它

  2. # 2 楼答案

    你可以使用split,这里就是一个例子

    String newString = string.split("\n\n")[1];
    
  3. # 3 楼答案

    你应该使用下面的正则表达式:

    str = str.replaceFirst("(?s).+?(\n\n)", "");
    

    因为,在newline字符与两个换行符背靠背相遇之前,需要匹配任何字符,包括newline


    请注意dot(.)newline不匹配,因此遇到first newline character时会停止匹配

    如果希望dot(.)与换行符匹配,可以使用Pattern.DOTALL,在str.replaceFirst的情况下,这是通过使用(?s)表达式实现的

    ^{}的文件中:

    In dotall mode, the expression . matches any character, including a line terminator. By default this expression does not match line terminators.

    Dotall mode can also be enabled via the embedded flag expression (?s).