Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading