Home > front end >  How to find values based on pattern matching from 2 string
How to find values based on pattern matching from 2 string

Time:03-17

I have string

a = "{key1}|{key2}_{key3}-{key4}"

I have another string

b = "abc|qwe_tue-pqr"

I need the output to be as to get values of

key1="abc", key2="qwe", key3="tue" and key4="pqr"

CodePudding user response:

If the use case is as simple as presented you could perhaps transform a into a regex with named capturing groups:

var r = new Regex(Regex.Escape(a).Replace("\\{","(?<").Replace("}",">[a-z] )"));

This turns a into a regex like (the | delimiter needed escaping):

(?<key1>[a-z] )\|(?<key2>[a-z] )_(?<key3>[a-z] )-(?<key4>[a-z] )

You can then get the matches and print them:

var m = r.Match(b);
foreach(Group g in m.Groups){
  Console.WriteLine(g.Name   "="   g.Value);
}
key1=abc
key2=qwe
key3=tue
key4=pqr

I can't promise it will reliably process everything you throw into it, based on the very limited input example, but it should give you the idea for a start on the process

  • Related