给定一个字符串x,ex:
var str = "This is the paragraph1. This is the paragraph2. This paragraph has not period";
我想只提取以句点(。)
结尾的段落这是我的代码:
var paragraphs = str.Split(new[] {'.'}, StringSplitOptions.RemoveEmptyEntries);
为什么结果是3项而不是2项?
str可以是变量
在这种情况下:
var str = "This is the paragraph1. This is the paragraph2. This paragraph3.";
结果应为3项
答案 0 :(得分:2)
为什么结果是3项而不是2项?
string.Split()
的工作原理。它在找到您提供的给定拆分文本的每个点处拆分字符串。你的字符串中有两个这样的点 - 即两个句点 - 所以字符串在两个地方分开。
当你在两个地方分割东西时,你得到三个部分。因此,三个部分将返回给您。
如果您只想要在一段时间内结束的文字,则需要使用其他算法。一种可能性就是不使用StringSplitOptions.RemoveEmptyEntries
选项,并忽略返回数组中的最后一项。
答案 1 :(得分:0)
似乎您只想提取第1段和第2段。
@"(?<=\.|^)[^.]*\."
<强>代码:强>
String input = @"This is the paragraph1. This is the paragraph2. This paragraph has not period";
Regex rgx = new Regex(@"(?<=\.|^)[^.]*\.");
foreach (Match m in rgx.Matches(input))
Console.WriteLine(m.Groups[0].Value);