【问题标题】:.NET Core - regex matches whole string instead of group [duplicate].NET Core - 正则表达式匹配整个字符串而不是组[重复]
【发布时间】:2020-11-05 06:54:37
【问题描述】:

我在 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;

感谢您在这方面帮助我

【问题讨论】:

  • 获取第一个捕获组应该是matches[0].Groups[1];
  • 如果你有 XML,一个更好的主意是通过例如 XDocument 或 XElement 而不是正则表达式来使用 LINQ to XML

标签: regex asp.net-core


【解决方案1】:

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

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();

【讨论】:

  • 有什么区别?看起来唯一改变的是阅读不同的组。你可以使用Groups[1] 来做同样的事情。不过,命名组很重要,因为其他原因 - 您实际上可以将组当作字段来处理,例如在 LINQ 查询中,例如 matches.OfType&lt;Match&gt;().Where(m=&gt;m.Groups['content"].Value=="SESSION_ID") 将获得与 SESSION_ID 匹配的所有匹配项。
  • 或者你可以直接使用 LINQ to XML
  • 如果输入字符串中包含嵌套节点,比如&lt;div&gt;&lt;OpenResult&gt;SESSION_ID&lt;/OpenResult&gt;&lt;/div&gt;,可以使用下面的表达式找到特殊节点:(&lt;.*&gt;)(?&lt;middle&gt;[\s\S]*)(&lt;\/.*&gt;),然后,使用match.Groups[1].Value获取Session_ID。
【解决方案2】:

如果您想要整个字符串作为结果,请使用非捕获组:(?:)

(?:&lt;.*&gt;)(?:[\s\S]*?)(?:&lt;\/.*&gt;)

Demo

如果您只想捕获会话 ID,请使用:

(?:&lt;.*&gt;)([\s\S]*?)(?:&lt;\/.*&gt;)

Demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-19
    • 2011-10-18
    • 2016-10-24
    • 1970-01-01
    • 1970-01-01
    • 2021-10-09
    • 2020-09-04
    相关资源
    最近更新 更多