Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to extract code in the middle of a String

Tags:

string

c#

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.

like image 844
DarrenL Avatar asked Jan 27 '23 23:01

DarrenL


1 Answers

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);
like image 196
vinicius.ras Avatar answered Feb 07 '23 19:02

vinicius.ras