C#Regex表达式,用于捕获多组字符之间的选择

时间:2018-06-06 16:33:28

标签: c# regex

我希望能够捕捉##组之间的所有内容。例如字符串:

  • ##First## the dog ate, ##second## the dog ran => ['First', 'second']
  • The dog ##ran## => ['ran']
  • ##The## dog ran away from ##home## => ['The', 'home']

我尝试了(?<=##).+?(?=#),但它捕获了第一个字符串。

我正在使用C#

1 个答案:

答案 0 :(得分:0)

由于背后的外观并且向前看,您将在first

中捕获second##First## the dog ate, ##second## the dog ran之间的字符串

要纠正这个问题,您需要使用它们:

(?:##)(?<text>.+?)(?:##)

然后,当您匹配时,您可以使用组text来提取您想要的部分。

例如:

var str = "##First## the dog ate, ##second## the dog ran";
var reg = new Regex("(?:##)(?<text>.+?)(?:##)");

var result = reg.Matches(str).Cast<Match>().Select(m => m.Groups["text"].Value);

result将包含Firstsecond