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?
Cheers!
You can use the Substring() method to get a substring in C#. The Substring() method takes the index position to start the retrieval of the substring as a parameter. Substring() can also take an optional parameter, which is the length of strings to return.
The substr() method extracts a part of a string. The substr() method begins at a specified position, and returns a specified number of characters. The substr() method does not change the original string. To extract characters from the end of the string, use a negative start position.
REGEXP_SUBSTR extends the functionality of the SUBSTR function by letting you search a string for a regular expression pattern. It is also similar to REGEXP_INSTR , but instead of returning the position of the substring, it returns the substring itself.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With