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

Retrieve and update the first number of a string

I have a string that may contain a prefix message with a number

e.g : Prefix1_SomeText

I need to check if the string contains the prefix message, and increment the number in that case.

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

Or if the string does not contain the prefix, I need to append it

e.g : Prefix2_SomeText.

So far I have this:

    string format = "prefix{0}_";
    string prefix = "prefix";

    string text = "prefix1_65478516548";

    if (!text.StartsWith(prefix))
    {
        text = text.Insert(0, string.Format(format, 1));
    }
    else
    {
        int count = int.Parse(text[6].ToString()) + 1;
        text = (String.Format(format, count) + "_" + text.Substring(text.LastIndexOf('_') + 1));
    }

Is there a simple way of doing it?

>Solution :

You could use a regular expression to check if the text contains the prefix and capture the index :

        string prefix = "prefix";

        string text = "prefix1_65478516548";
        Regex r = new Regex($"{prefix}(\\d+)_(.*)");
        var match = r.Match(text);
        if (match.Success)
        {
            int index = int.Parse(match.Groups[1].Value);
            text = $"{prefix}{index + 1}_{match.Groups[2].Value}";
        }
        else
        {
            text = $"{prefix}1_{text}";
        }
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