提取字符串子组
Extract subgroups of string
给定一个字符串 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 项
您似乎只想提取第 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);
Why the result is 3 items and not is 2 items?
这就是 string.Split()
的工作原理。它在找到您提供的给定拆分文本的每个点 拆分 字符串。你的字符串中有两个这样的点——即两个句点——所以字符串被分成两个地方。
当你将某样东西分成两部分时,你会得到三部分。所以三部分还给你。
如果您只想要 结束 的文本,则需要使用不同的算法。一种可能是 而不是 使用 StringSplitOptions.RemoveEmptyEntries
选项,并忽略返回数组中的最后一项。
给定一个字符串 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 项
您似乎只想提取第 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);
Why the result is 3 items and not is 2 items?
这就是 string.Split()
的工作原理。它在找到您提供的给定拆分文本的每个点 拆分 字符串。你的字符串中有两个这样的点——即两个句点——所以字符串被分成两个地方。
当你将某样东西分成两部分时,你会得到三部分。所以三部分还给你。
如果您只想要 结束 的文本,则需要使用不同的算法。一种可能是 而不是 使用 StringSplitOptions.RemoveEmptyEntries
选项,并忽略返回数组中的最后一项。