5

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

var strReplace = @"$2";
Regex.Replace(strInput, @"((.)*?)", strReplace);
StronglyTyped
  • 2,134
  • 5
  • 28
  • 48
  • If you are using Javascript then try the below http://stackoverflow.com/questions/423107/use-regexp-to-match-a-parenthetical-number-then-increment-it – PraveenVenu Mar 08 '12 at 13:36

3 Answers3

4

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
Qtax
  • 33,241
  • 9
  • 83
  • 121
2

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.

Tinned_Tuna
  • 237
  • 1
  • 12
0

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.

Jonas Elfström
  • 30,834
  • 6
  • 70
  • 106