首页 > 解决方案 > C# 正则表达式将捕获多组字符之间的选择

问题描述

我希望能够捕获##. 例如字符串:

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

我正在使用 C#

标签: c#regex

解决方案


由于向后看和向前看,您将捕捉到中间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


推荐阅读