Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java正则表达式将多个新行字符匹配到个字符_Java_Regex - Fatal编程技术网

java正则表达式将多个新行字符匹配到个字符

java正则表达式将多个新行字符匹配到个字符,java,regex,Java,Regex,我有以下文本字符串,由一个文本块后跟两个或多个 新行字符(\n可能\r)后跟另一个文本块,等等,如下所示 多行文字 (两个或更多新行字符) 多线tex (两个或更多新行字符) 我想使用新行作为中断边界,将此字符串拆分为与文本块数量相同的子字符串 我试过了 public static int indexOf(Pattern pattern, String s) { Matcher matcher = pattern.matcher(s); return matche

我有以下文本字符串,由一个文本块后跟两个或多个 新行字符(\n可能\r)后跟另一个文本块,等等,如下所示

多行文字

(两个或更多新行字符)

多线tex

(两个或更多新行字符)

我想使用新行作为中断边界,将此字符串拆分为与文本块数量相同的子字符串

我试过了

public static int indexOf(Pattern pattern, String s) {
        Matcher matcher = pattern.matcher(s);
        return matcher.find() ? matcher.start() : -1;
    }


pStart[i-1] = start + indexOf(Pattern.compile("[\\n\\n]+"), text.substring(start)); 
但它不起作用


有更好的方法处理它吗?

您需要了解
[\\n\\n]
只意味着一个新行字符
\n
,因为它在字符类中。在character类中,列出的字符中只有一个匹配

您可以使用:

\\n{2}

而是匹配新行字符。

您需要了解
[\\n\\n]
只表示一个新行字符
\n
,因为它在字符类中。在character类中,列出的字符中只有一个匹配

您可以使用:

\\n{2}

而是匹配新的换行符。

任何简单的方法都是使用带有正则表达式的字符串拆分函数:

String sampleText = new String("first\nsecond\n\r");
String [] blocks = sampleText.split("\n{1,}[\r]?");
以上假设为“1或多个\n”和可选的“1\r”。
您可以将正则表达式更改为“\n{2,}[\r]?”,用于两个或多个“\n”,具体取决于所需内容


干杯

任何简单的方法都是将字符串拆分函数与正则表达式一起使用:

String sampleText = new String("first\nsecond\n\r");
String [] blocks = sampleText.split("\n{1,}[\r]?");
以上假设为“1或多个\n”和可选的“1\r”。
您可以将正则表达式更改为“\n{2,}[\r]?”,用于两个或多个“\n”,具体取决于所需内容

干杯