0

String: "Some text This is first hex number 0x00000001, This is second hex number 0x00000002 Some text" Pattern: "This is first hex number 0x00000001, This is second hex number 0x00000002" Expected output: "0x00000001" and "0x00000002" (string or int, doesn't matter)

In C# I want to search a String for known Pattern (as in Pattern, hex values may be different, but always in format 0xXXXXXXXX) and if it is found obtain both hex values as string or int.

I am somehow fimiliar with Regex and have one solution, but it seems very 'dirty'. I am almost sure that there should be simplier solution.

string input = "Some text This is first hex number 0x00000001, This is 
second hex number 0x00000002 Some text";
var pattern = new Regex(@"This is first hex number 0x[0-9A-F]{8}, This is second hex number 0x[0-9A-F]{8}");

if (pattern.Match(input).Success)
{
    Console.WriteLine("Patter found!");
    Console.WriteLine("First Hex: {0}", pattern.Match(input).ToString().Split(' ')[6].Trim(','));
    Console.WriteLine("Second Hex: {0}", pattern.Match(input).ToString().Split(' ')[10]);
}
user1762979
  • 71
  • 1
  • 4
  • Looks like you are looking to create a regex, but do not know where to get started. Please check [Reference - What does this regex mean](https://stackoverflow.com/questions/22937618) resource, it has plenty of hints. Also, refer to [Learning Regular Expressions](https://stackoverflow.com/questions/4736) post for some basic regex info. Once you get some expression ready and still have issues with the solution, please edit the question with the latest details and we'll be glad to help you fix the problem. – Wiktor Stribiżew Mar 25 '20 at 14:10
  • @WiktorStribiżew I have edited my question with code that I have made so far - it works but I am looking for simpler solution which I couldn't find by quick google search. – user1762979 Mar 25 '20 at 15:11
  • 1
    See https://ideone.com/zVdU9d, is it what you need? – Wiktor Stribiżew Mar 25 '20 at 15:23
  • @WiktorStribiżew Yes, it looks much better, although I do not know what will be in "Some text" (it may also contain hex values). Do I need to call Match first with patter as in my example and then again with only hex pattern? Or can it be done in one call? – user1762979 Mar 25 '20 at 15:31
  • 1
    No idea what you mean. What does `Some text` have to do with your problem of extracting hex values? Do you need https://ideone.com/tzhSq8? – Wiktor Stribiżew Mar 25 '20 at 15:36
  • @WiktorStribiżew This is it. I din't know how to obtain values in such way. Huge thank you! – user1762979 Mar 26 '20 at 17:44
  • Ok, so your question is a duplicate of https://stackoverflow.com/questions/628556/returning-only-part-of-match-from-regular-expression, I changed the link at the top. Glad to be of help. But please make sure you study these basics. – Wiktor Stribiżew Mar 26 '20 at 18:55

0 Answers0