2016-02-12 27 views
3

我有一个很长的句子,其中嵌入了新的行或回车符,我想将它们分成单独的句子。这样一个例子: This is a new line=?xxx\n What's \n up应该产生This is a new line=?xxxWhat'sup使用Java以新行作为分隔符来分割句子(1.7)匹配器

我不想使用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 

什么问题与我的正则表达式?

+0

在最后\ n之后找不到任何东西。所以m.find()返回false。 –

+3

'我不想使用String.split(“\ n”)'你能澄清原因吗? – anubhava

+0

为什么不使用'。+'来匹配*行*? –

回答

0

匹配输入使用勉强量词。

试试这个正则表达式:

"(?m).*$" 

(?m)标志使$线(平台独立)的每一个结束比赛,并点仍然不会匹配换行符(所以没有必要勉强量词)。使用m.group(0)或只是m.group()


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

"(?m).+$" 

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

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

参见live demo

+0

有没有办法忽略空的空间? – Neel

+0

@Neel是的。我编辑了答案 – Bohemian

+0

这些正则表达式可以工作,但不情愿的量词无关紧要。 –

1

如果要匹配,那么使用这个表达式:

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

(?:[\r\n]|$)将匹配行结束(\r\n)或输入端从而确保最后一行也匹配。

但是stringsplit("[\\r\\n]+");应该是这里的首选方式。

RegEx Demo

1

为什么你的正则表达式不正确的?

(.*[\r\n]+|$)包含2个备选方案:

  • .*[\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 demo

如果你想匹配,使用与任何字符匹配的.更容易,但换行符a第二回车,一些更 “垂直空白” 字符:

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

Java demo

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)); 
} 

参见what . actually does not match

  • 的换行(换行)字符('\ n'),
  • 回车符后面紧跟换行符(“\ r \ n”),
  • 一个独立的回车符( '\ r'),
  • 下一行字符( '\ u0085'),
  • 甲线分隔符( '\ u2028'),或
  • 甲段落分隔符('\ u2029)。
  • 如果UNIX_LINES模式被激活,则唯一被识别的行终止符是换行符。
1

为什么走这条路时,有在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()); 
} 
0

的支持开箱即用试试这个:

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

它为我工作。

相关问题