Immi
Immi

Reputation: 187

Regex: get every number that doesn't has an other number before or after itself

The thing that I have to do is to extract every 'single' number, that doesn't has another number right before or after itself. Then I have to replace this number with an number, that is incremented with 1.

I now want to a Regex that gets every single number from a string, that doesn't has another number right before or after itself.

As example:

From this string, I just want the '1': "Klasse 1a 14/15" the result should look like "Klasse 2a 14/15"

From this string, I just want the '5': "5/66" the result should look like "6/66"

From this string, I want the '1', '2' and '3': "1/2/3" and the result should look like "2/3/4"

From this string, I just want the '4': "4. Klasse" and the result should look like "5. Klasse"

From this string, I don't want to get anything: "Klasse 99" and the result will remain "Klasse 99"

What I have at the Moment is this Regex:

[\D*](\d{1})[\D*]

and this method:

internal string GenerateFollowingSubjectGradeTitle(string currentGradeTitle)
    {
        var followingGradeTitle = string.Format("{0}{1}{0}", "_", currentGradeTitle);

        var regex = new Regex(@"[\D*](\d){1}[\D*] /gm");

        var matches = regex.Matches(followingGradeTitle);

        if (matches.Count > 0)
        {
            for (var i = 0; i < matches.Count; i++)
            {
                var exactmatch = matches[i].Groups[1].Value;
                var groupmatch = matches[i].Groups[0].Value;

                var intmatch = 0;
                if (int.TryParse(exactmatch, out intmatch))
                {
                    var groupreplace = groupmatch.Replace(exactmatch, (intmatch + 1).ToString());
                    followingGradeTitle = followingGradeTitle.Replace(groupmatch, groupreplace);
                }
            }
        }

        return followingGradeTitle.Substring(1, followingGradeTitle.Length - 2);
    }

..and it works mostly but not everytime. In "1/2/3" I just get the 1 and the 3, but I need the 2 as well.

I know my attempt is not the best way, if you have better solutions, let me know :)

Any suggestions?

Upvotes: 1

Views: 109

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174806

You could try the below negative lookarounds based regex.

(?<!\d)\d(?!\d)

DEMO

OR

This would work if you're running javascript. Pick the number you want from group index 1. Lookarounds are assertion which won't consume any character.

(?:^|\D)(\d)(?=\D|$)

DEMO

Upvotes: 4

Related Questions