52

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 this snippet:

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

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!");
}

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

2 Answers 2

81

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("<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);
    }      
  }
}

Output:

Found Match for <key>LibID</key><val>A67A</val>
ID was A67A
Sign up to request clarification or add additional context in comments.

4 Comments

Beat me to it. You're already using a grouped match there Andrew, so you can easily extract the grouped value. Oh, and for the record, index 0 contains the entire string, that's why you check index 1.
Super thanks. I knew it was in there somewhere, I just didn't know where :)
Hmm not sure why but my Match Groups contains only 1 value at index 0 which is the one I need. Anyway thanks
@CularBytes: Without knowing what pattern you're using or what you're matching against, there's no way we can explain the behavior to you. If you're interested in finding out more, please post a new question with a minimal reproducible example.
3

Add a grouping construct to your expression ...

<key>(?<id>LibID)</key><val>([a-fA-F0-9]{4})</val>

That will capture the ID. But, you need to put the correct format in your expression for the actual ID, because your regex will only capture "LibID" litterally.

1 Comment

I think by "ID" Andrew means the contents of the <val> element, not the <key> element.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.