P
P
pw0ned2018-09-11 18:22:14
C++ / C#
pw0ned, 2018-09-11 18:22:14

Doubling digits in c# how?

Still practicing with text documents.
How to use a regular expression to replace multiple digits?
For example I have the following:

string result = Regex.Replace(line,@"1$", @"111").Replace(@"2$", @"222");
                Console.WriteLine(result);

The regular expression only works when Regex.Replace is present, and therefore only replaces 1 with 111, replacing 2 with 222 does not work.
How to use the regular expression in this case?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
MrDywar Pichugin, 2018-09-11
@Dywar

Regex.Replace returns the string on which you call the Replace method, which has nothing to do with Regex.
You need to understand C# a little more.
Templates for replacing numbers with others and etc. are googled, with difficulty, but googled. On kraynyak there is documentation that will have to be read.

R
Rayvor, 2018-09-12
@Rayvor

Use extension methods:

using System.Text.RegularExpressions;

public static class RegexEx
{
        public static string ReplaceEx(this string input, string pattern, string replacement)
        {
            return Regex.Replace(input, pattern, replacement);
        }
}

Usage:
string line = "123";
string result = line.ReplaceEx("1", "111").ReplaceEx("2", "222").ReplaceEx("3", "333");
Console.WriteLine(result); // 111222333

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question