KorkOoO
KorkOoO

Reputation: 612

regex multiple replacements

I'm trying to perform multiple replacements using regular expressions in a string. Currently, I'm using a regex command (mentioned below) in Notepad++ , and it works as expected; however, when I tried to test the same regex on regexstorm it didn't work.

Assume that I want to find & replace the following:

Input:

5441.32 6140 
1:34,360

Find: (0)|(1)|(2)

Replace: (?1A)(?2B)(?3C)

NP++ Output:

544B.3C 6B4A
B:34,36A

regexstorm Output:

544(?1A)(?2B)(?3C).3(?1A)(?2B)(?3C) 6(?1A)(?2B)(?3C)4(?1A)(?2B)(?3C) 
(?1A)(?2B)(?3C):34,36(?1A)(?2B)(?3C)

I'm still reading and learning about regular expressions so, could somebody please tell me what am I doing wrong on regexstorm?

Upvotes: 2

Views: 2553

Answers (4)

OOMMEN
OOMMEN

Reputation: 259

You can do this as follow,

 static void Main(string[] args)
    {
        string pattern = @"(0|1|2)";
        string input = "5441.32 6140";
        Regex rgx = new Regex(pattern);
        var map = new Dictionary<string, string> {
                  { "0", "A"},
                  { "1", "B"},
                  { "2", "C" }
                 };

        string result = rgx.Replace(input,m => map[m.Value]);

        Console.WriteLine("Original String:    '{0}'", input);
        Console.WriteLine("Replacement String: '{0}'", result);
        Console.ReadLine();
    }

Its better to use StringBuilder. Link:Replace Multiple String Elements in C#

Upvotes: 1

Souvik Ghosh
Souvik Ghosh

Reputation: 4606

You can simply do string replace-

string input = "5441.32 6140";
string output = input.Replace('0', 'A').Replace('1', 'B').Replace('2', 'C');
Console.WriteLine(output); //output is 544B.3C 6B4A

Upvotes: 1

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186688

Why not Linq which is simpler than regular expression:

string source = "5441.32 6140";

string result = string.Concat(source
  .Select(c => c >= '0' && c <= '2' 
     ? (char) (c - '0' + 'A')
     : c));

If you want to update the condition and add, say 3 > D, all you have to do is to change c <= 2 into c <= 3. If you insist on regular expression, I suggest working with match, not with pattern:

string source = "5441.32 6140";

string result = Regex.Replace(source, 
  "[0-2]",                                            // easy pattern
   m => ((char)(m.Value[0] - '0' + 'A')).ToString()); // elaborated match

Upvotes: 2

JohnyL
JohnyL

Reputation: 7142

var s = "5441.32 6140";
var pattern = @"(0|1|2)";
var s2 = Regex.Replace(s, pattern, m =>
{
    string sMatch = m.Value;
    string final = null;
    if (sMatch == "0")
        final = "A";
    else if (sMatch == "1")
        final = "B";
    else if (sMatch == "2")
        final = "C";
    return final;
});

Upvotes: 0

Related Questions