查找与模式匹配的所有子串

时间:2017-05-26 05:38:24

标签: c# regex

我想使用C#从单个字符串中提取所有出现的子字符串,其格式为:空格后跟任何文本。

因此,例如,如果我有一个字符串“This is a very short sentence”,那么我希望能够获得5个字符串:

“is a very short sentence”
“a very short sentence”
“very short sentence”
“short sentence”
“sentence”

从上面的示例中,子字符串不应包含前导空格。也能够通过索引访问每个获得的字符串会很棒。

我尝试使用正则表达式,但我无法绕过第一场比赛。

请帮忙

2 个答案:

答案 0 :(得分:3)

使用Split和一些Linq

string text2 = "This is a very short sentence";

// Get all words except first one
var parts = text2.Split(' ').Skip(1);

// Generate various combinations 
var result = Enumerable.Range(0, parts.Count())
    .Select(i => string.Join(" ", parts.Skip(i)));

答案 1 :(得分:1)

尝试使用循环和子串方法:

string inputStr = "This is a very short sentence";
List<string> subStringList = new List<string>();

while(inputStr.IndexOf(' ')!=-1)
{
    inputStr= inputStr.Substring(inputStr.IndexOf(' ')+1);
    subStringList.Add(inputStr);
}


Console.WriteLine(String.Join("\n",subStringList));

Working Example

相关问题