正则表达式在字符串之前获取文本

时间:2016-01-29 19:39:55

标签: c# regex string

我在c#中有字符串文本,我试图在表达eachDELETEDDELETED之前获取所有单词,并且我想将它们转换为列表或数组。有人可以帮助正则表达式部分。

文字示例: word word word word word word 20 word-16S eachDELETEDDELETEDword word word word word word 20 word-16z1 (size 26), eachDELETEDDELETED

Regex ry = new Regex(@"eachDELETEDDELETED");
MatchCollection matchList = Regex.Matches(extracted, ry.ToString());
var list = matchList.Cast<Match>().Select(match => match.Value).ToList();

foreach (string s in list)
{
    richTextBox2.Text += s + "\n";
}

2 个答案:

答案 0 :(得分:1)

只需使用Regex.Split:

string example = "word word word word word word 20 word-16S eachDELETEDDELETEDword word word word word word 20 word-16S eachDELETEDDELETED";
string[] parts = Regex.Split(example, "eachDELETEDDELETED");
foreach(string part in parts)
{
    Console.WriteLine(part);
}

将输出:

word word word word word word 20 word-16S 
word word word word word word 20 word-16S

答案 1 :(得分:0)

仅供参考,这也可以通过前瞻和\G锚来完成:

^|\G(?:([-\w]+)\s*)(?!(?:eachDELETEDDELETED))

请参阅a demo on regex101.com