Fetch number from string in c#

I have a string tag like PECVD_XL_XT_6_1_B9_PATCH.3

I want to fetch release, build and patch number from this tag

The output is
Release is 6_1
Build is 9
Patch is 3

Patch is not mandatory to be present in the tag the tag can be only

PECVD_XL_XT_6_1_B9

PECVD_XL_XT_ can be same or vary from string to string

I am trying below approach but seems like so length and not effective.

string input = "PECVD_XL_XT_6_1_B9_PATCH.2".ToLower();
Regex re = new Regex(@"\d+");
Match m = re.Match(input);

string s = input.Substring(m.Index);

int batchIndex = s.IndexOf('B');

string[] releaseBuildPatchArray = s.Split('b');

Can someone suggest any other approach for this?

>Solution :

You could use this approach using string methods:

 string input = "PECVD_XL_XT_6_1_B9_PATCH.2".ToLower();
 List<string> tokens = input.Split('_').ToList();
 int buildIndex = tokens.FindIndex(s => s.StartsWith('b') && s.Substring(1).All(char.IsDigit));
 if(buildIndex >= 2)
 {
    List<string> releaseParts = tokens.GetRange(buildIndex - 2, 2);
    string release = string.Join("_", releaseParts);
    string build = tokens[buildIndex].TrimStart('b');
    int patchIndex = input.LastIndexOf('.');
    string patchNumber = patchIndex >= 0
        ? input.Substring(++patchIndex) : null;
 }

https://dotnetfiddle.net/uICrMg

Leave a Reply