首页 > 解决方案 > .NET Core - 正则表达式匹配整个字符串而不是组

问题描述

我在 regex101.com 上测试了我的正则表达式,它返回 3 个组

文本 :

<CloseResponse>SESSION_ID</CloseResponse>

正则表达式:

(<.*>)([\s\S]*?)(<\/.*>)

在 C# 中,我只得到一个匹配项和一个包含整个字符串而不仅仅是 SESSION_ID 的组

我希望代码只返回SESSION_ID

我尝试找到一个全局选项,但似乎没有

这是我的代码

Regex rg = new Regex(@"<.*>([\s\S]*?)<\/.*>");
MatchCollection matches = rg.Matches(tag);
if (matches.Count > 0) ////////////////////////////////// only one match
{
    if (matches[0].Groups.Count > 0)
    {
        Group g = matches[0].Groups[0];
        return g.Value; //////////////////// = <CloseResponse>SESSION_ID</CloseResponse>
    }
}
return null;

谢谢你帮助我

标签: regexasp.net-core

解决方案


我设法使它以这种方式工作

string input = "<OpenResult>SESSION_ID</OpenResult>";

// ... Use named group in regular expression.
Regex expression = new Regex(@"(<.*>)(?<middle>[\s\S]*)(<\/.*>)");

// ... See if we matched.
Match match = expression.Match(input);
if (match.Success)
{
    // ... Get group by name.
    string result = match.Groups["middle"].Value;
    Console.WriteLine("Middle: {0}", result);
}
// Done.
Console.ReadLine();

推荐阅读