I am trying to extract a code from a string. The string can vary in content and size but I am using Tag words to make the extraction easier. However, I am struggling to nail a particular scenario. Here is the string:
({GoldPrice} * 0.376) + {MP.011} + {SilverPrice}
What I need to extract is the 011 part of {MP.011}. The keyword will always be "{MP." It's just the code that will change. Also the rest of the expression can change so for example {MP.011} could be at the beginning, end or middle of the string.
I've got close using the following:
int pFrom = code.IndexOf("{MP.") + "{MP.".Length;
int pTo = code.LastIndexOf("}");
String result = code.Substring(pFrom, pTo - pFrom);
However, the result is 011} + {SilverPrice
as it is looking for the last occurrence of }, not the next occurrence. This is where I am struggling.
Any help would be much appreciated.
You could use a regular expression to parse that:
var str = "({GoldPrice} * 0.376) + {MP.011} + {SilverPrice}";
var number = Regex.Match(str, @"{MP\.(\d+)}")
.Groups[1].Value;
Console.WriteLine(number);
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