c# – How can I replace a part of a string with itself plus the "~" character?

Question:

How can I replace a part of a string with itself plus the "~" character?

I'm doing it as follows: but when the string has two equal numbers like 51 that comes right after AP and contained in 17 51 3322 the Replace makes the exchange in both places and I just want you to do the Replace in the complete number.

My string should look like this:

RUASANTA HELENA, 769~ AP 51~ BL H JD DAWN~ 17513322~

using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        string lista = "RUASANTA HELENA, 769  AP 51 BL H JD ALVORADA~ 17513322 ";

        var match = Regex.Match(lista, "[0-9]+");
        while (match.Success)
        {
            lista = lista.Replace(match.Value, match.Value + "~");
            match = match.NextMatch();
        }
        System.Console.Write(lista);    
    }       
}

Answer:

If the complete number is always followed by a space, you can use the pattern " ([0-9]+?) " and replace it with the match that occurred inside the parentheses plus the ~ and a space (which also gave a match):

string lista = "RUASANTA HELENA, 769  AP 51 BL H JD ALVORADA~ 17513322 ";
lista = Regex.Replace(lista, "([0-9]) ", "$1~ ");

Exemplo no DotNetFiddle.

Scroll to Top