How to extract a substring from a .NET RegEx?

后端 未结 2 1820
不知归路
不知归路 2020-12-30 18:31

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.

So the XML contains t

2条回答
  •  梦毁少年i
    2020-12-30 19:27

    I think you want

    match.Groups[1].Value
    

    (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("LibID([a-fA-F0-9]{4})");
        Match match = regex.Match("BeforeLibIDA67AAfter");
    
        if (match.Success)
        {
          Console.WriteLine("Found Match for {0}", match.Value);
          Console.WriteLine("ID was {0}", match.Groups[1].Value);
        }      
      }
    }
    

    Output:

    Found Match for LibIDA67A
    ID was A67A
    

提交回复
热议问题