Loading ...

Regex: Reverse all numbers in string | CodeAsp.Net

Regex: Reverse all numbers in string

0 (0votes)

In this blog I will show how to reverse all numbers in string with REGEX. Let's say we have a string "Hello 123456789 user 456 welcome." and we want to reverse it like "Hello 987654321 user 654 welcome.". Below is the sample code to do the same:

using System;
using System.Linq;
using System.Text.RegularExpressions;

namespace SampleConsoleApplication
    class Program
        static void Main(string[] args)
            const string inputString = @"Hello 123456789 user 456 welcome.";

            string output = Regex.Replace(inputString,@"\d+", m => new string(m.Value.Reverse().ToArray()));



Below is the explanation of regex:


Match a single digit 0..9 «\d+»
   Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»

Created with RegexBuddy

Comments (no comments yet)

Top Posts