Percy22
Percy22

Reputation: 63

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.

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?

Upvotes: 1

Views: 40

Answers (1)

J.Loscos
J.Loscos

Reputation: 2907

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}";
        }

Upvotes: 1

Related Questions