如何提取从.NET正则表达式的子串? [英] How to extract a substring from a .NET RegEx?

查看:132
本文介绍了如何提取从.NET正则表达式的子串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一个(或多个)键/值对的XML文件。对于每一个这些对我要提取的值中的哪一个两个字节的十六进制值。

I have an XML file containing one (or more) key/value pairs. For each of these pairs I want to extract the value which is a two-byte hex value.

所以XML包含这段代码:

So the XML contains this snippet:

<key>LibID</key><val>A67A</val>

其中我可以用下面的前pression,用括号中的ID相匹配。

Which I can match using the following expression, with the ID in parenthesis.

Match match = Regex.Match(content, @"<key>LibID</key><val>([a-fA-F0-9]{4})</val>");

if (match.Success)
{
  Console.WriteLine("Found Match for {0}\n", match.Value);
  Console.WriteLine("ID was {0}\n", "Help me SO!");
}

我如何可以改变的最后一部分,因此从比赛返回ID?

How can I change the last part so it returns the ID from the match?

干杯!

推荐答案

我想你想

match.Groups[1].Value

(如Dillie-O指出,在评论中,这是第1组,因为组0总是整场比赛。)

(As Dillie-O points out in the comments, it's group 1 because group 0 is always the whole match.)

短,但完整的测试方案:

Short but complete test program:

using System;
using System.Text.RegularExpressions;

class Program
{
  static void Main()
  {
    Regex regex = new Regex("<key>LibID</key><val>([a-fA-F0-9]{4})</val>");
    Match match = regex.Match("Before<key>LibID</key><val>A67A</val>After");

    if (match.Success)
    {
      Console.WriteLine("Found Match for {0}", match.Value);
      Console.WriteLine("ID was {0}", match.Groups[1].Value);
    }      
  }
}

输出:

Found Match for <key>LibID</key><val>A67A</val>
ID was A67A

这篇关于如何提取从.NET正则表达式的子串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆