Is it possible to execute padding in regex?

Assuming the placeholder $ 2 is filled with an integer, is it possible to increase it by 1 ?:

var strReplace = @"$2";
Regex.Replace(strInput, @"((.)*?)", strReplace);
+5
source share
3 answers

You can use the reverse version Regex.Replacewith MatchEvaluator, see examples in:

Here is an example ( ideone ):

using System;
using System.Text.RegularExpressions;

class Program
{
    static string AddOne(string s)
    {
        return Regex.Replace(s, @"\d+", (match) =>
        {
            long num = 0;
            long.TryParse(match.ToString(), out num);
            return (num + 1).ToString();
        });
    }

    static void Main()
    {
        Console.WriteLine(AddOne("hello 123!"));
        Console.WriteLine(AddOne("bai bai 11"));
    }
}

Conclusion:

hello 124!
bai bai 12
+4
source

In standard (theoretical-theoretical) regular expressions, this is not possible with regular expressions.

, Perl , , , , , , .

+2

This is not possible with standard regex, but you can if you write a custom MatchEvaluator.

string str = "Today I have answered 0 questions on StackOverlow.";
string pattern = @"\w*?(\d)";
var result = Regex.Replace(str, pattern, 
                   m => (int.Parse(m.Groups[0].Value)+1).ToString() );
Console.WriteLine(result);

Today I answered 1 question on StackOverlow.

0
source

All Articles