如何提取从.NET正则表达式的子串?正则表达式、NET

2023-09-04 08:44:42 作者:萌主殿下

我有一个包含一个(或多个)键/值对的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