【发布时间】: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