StronglyTyped
StronglyTyped

Reputation: 2134

Is it Possible to Perform Addition in a Regex?

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

var strReplace = @"$2";
Regex.Replace(strInput, @"((.)*?)", strReplace);

Upvotes: 5

Views: 8658

Answers (3)

Jonas Elfström
Jonas Elfström

Reputation: 31438

It's not possible with a standard regular expression 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 have answered 1 questions on StackOverlow.

Upvotes: 0

Qtax
Qtax

Reputation: 33918

You can use a callback version of Regex.Replace with a MatchEvaluator, see examples at:

Here's 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"));
    }
}

Output:

hello 124!
bai bai 12

Upvotes: 4

Tinned_Tuna
Tinned_Tuna

Reputation: 237

In standard (CS theoretic) regular expressions, it is impossible with a regular expression.

However, Perl and such have extensions to Regular Expressions, which has implications for their behaviour, and I am not familiar enough with them to definitely say that the extended regexes will not do it, but I'm fairly sure that this behaviour is not possible with a regex.

Upvotes: 2

Related Questions