簡體   English   中英

使用Java(1.7)Matcher將新行拆分為分隔符

[英]Split sentences with new line as delimiter using Java (1.7) Matcher

我有一個很長的句子,有嵌入的新行或回車,我想分成單獨的句子。 例如: This is a new line=?xxx\\n What's \\n up應該生成What's This is a new line=?xxx What's up

我不想使用String.split("\\n") ,而是使用類似的東西:

String x = "  This is a new line=?xxx\n Whats' \n up";
// This is not correct
Pattern p = Pattern.compile("(.*[\r\n]+|$)");
Matcher m = p.matcher(x);
while (m.find()) {
      System.out.printline(m.group(1));
}

上面的代碼產生:

   This is a new line=?xxx
   What's

我的正則表達式有什么問題?

如果你想匹配,那么使用這個正則表達式:

(.+?)(?:[\r\n]|$)

(?:[\\r\\n]|$)將匹配行結束( \\r\\n )或輸入結束,從而確保最后一行也匹配。

但是stringsplit("[\\\\r\\\\n]+"); 應該是這里的首選方式。

RegEx演示

為什么你的正則表達式不正確?

(.*[\\r\\n]+|$)包含兩個選項:

  • .*[\\r\\n]+ - 除換行序列以外的零個或多個字符(見下文),然后是一個或多個換行符(CR或/和LF)
  • | - 要么...
  • $ - 結束字符串

所以,你實際上錯誤地放置了分組,這就是你想要它的樣子:

String p = "(.*(?:[\r\n]+|$))";
String x = "  This is a new line=?xxx\n Whats' \n up";
Matcher m = Pattern.compile(p).matcher(x);
while (m.find()) {
      System.out.println(m.group(1));
}

請參閱IDEONE演示

如果你想匹配線條 ,則更容易使用. 匹配任何字符,但換行和回車,以及一些更“垂直的空白”字符:

Pattern p = Pattern.compile(".+"); // for non-empty lines
Pattern p = Pattern.compile(".*"); // for empty lines as well

請參閱Java演示

String x = "  This is a new line=?xxx\n Whats' \n up";
Pattern ptrn = Pattern.compile(".+");
Matcher matcher = ptrn.matcher(x);
while (matcher.find()) {
    System.out.println(matcher.group(0));
}

看看是什么. 實際上不匹配

  • 換行符(換行符)('\\ n'),
  • 一個回車符后面跟一個換行符(“\\ r \\ n”),
  • 一個獨立的回車符('\\ r'),
  • 下一行字符('\\ u0085'),
  • 行分隔符('\\ u2028')或
  • 段落分隔符('\\ u2029)。
  • 如果激活了UNIX_LINES模式,則唯一識別的行終止符是換行符。

為什么在java.util.regex.Pattern中支持開箱即可使用此路由

Matcher m = Pattern.compile("(^.+$)+", Pattern.MULTILINE).matcher("This is a new line=?xxx\n Whats' \n up");
while (m.find()) {
    System.out.println(m.group());
}

使用不情願的量詞匹配輸入。

試試這個正則表達式:

"(?m).*$"

(?m)標志使每個行的每個行匹配$ (獨立於平台),並且點仍然不匹配換行符(因此不需要不情願的量詞)。 使用m.group(0)m.group()


要匹配非空句子,請使用“+”:

"(?m).+$"

要匹配非空白(至少1個非空格):

"(?m).*\\S.*$"

查看現場演示

嘗試這個:

Pattern.compile("(.+[\r\n]?+)");

它對我有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM