regex - .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;
谢谢你帮助我
解决方案
我设法使它以这种方式工作
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();
推荐阅读
- assembly - 如何获取在特定时间持有哪些密钥?
- spring - 如何在Springboot中禁止`DELETE` http请求?
- assembly - MIPS 程序集:内存在堆栈中被另一个子程序覆盖
- eclipse - Intellij Idea 给出错误错误:gradle.build 不是项目的一部分
- react-native - React Native 导航操作
- javascript - React Native 使用 Firebase 从 JSON 树中获取特定的子值
- c# - C# 用 Windows 窗体中使用的所有按钮填充数组
- c++ - 如何访问结构的成员
- javascript - 如何在 JSX (React) 中执行 JS 而不将其输出为 HTML?
- google-bigquery - BigQuery:无效日期错误