phuongnd phuongnd - 1 year ago 161
C# Question

Get string value from Placeholder C#

I have pattern string:"Hello {Name}, welcome to {Country}"

and a full value string:"Hello Scott, welcome to VietNam"

How can I extract value of {Name} and {Country}:

Name = Scott, Country = VietNam

I have see some regular expression to resolve this problem but can I apply fuzzy matching here?
e.g. With invert string "welcome to VietNam, Hello Scott", we must change the regular expression too?

Answer Source

You can use Regex:

var Matches = Regex.Matches(input, @"hello\s+?([^\s]*)\s*|welcome\s+?to\s+?([^\s]*)", RegexOptions.IgnoreCase);

string Name = Matches.Groups[1].Value;
string Country  = Matches.Groups[2].Value;

Update: Changed code to work either way. Demo.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download