提取字符串的子组

本文关键字:字符串 提取 | 更新日期: 2024-10-23 22:43:27

给定字符串x,例如:

 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项

提取字符串的子组

为什么结果是3项而不是2项?

string.Split()就是这样工作的。它在找到您提供的给定拆分文本的每个点拆分字符串。你的思路中有两点:;即两个周期—所以绳子被分成两个地方。

当你把东西分成两部分时,你会得到三部分。所以有三个部分返回给您。

如果您只想要在句点中结束的文本,则需要使用不同的算法。一种可能性是简单地而不是使用StringSplitOptions.RemoveEmptyEntries选项,并忽略返回数组中的最后一项。

似乎只想提取第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);

IDEONE