[英]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]+");
应该是这里的首选方式。
为什么你的正则表达式不正确?
(.*[\\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));
}
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.