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

大城市里の小女人 提交于 2019-12-11 05:43:46

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/30521851/regex-get-every-number-that-doesnt-has-an-other-number-before-or-after-itself

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!