Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace two or more strings with each other?

Tags:

string

c#

replace

I need to replace some parts of a string with each other using C#. I could find only one similar question about how to achive this here but it was PHP.

My situation involves a Dictionary[string, string] which holds pairs to replace like:

  • dog, cat
  • cat, mouse,
  • mouse, raptor

And I have a string with the value of:

"My dog ate a cat which once ate a mouse got eaten by a raptor"

I need a function to get this:

"My cat ate a mouse which once ate a raptor got eaten by a raptor"

If I enumerate the dictionary and call string.Replace by order, I get this:

"My raptor ate a raptor which once ate a raptor got eaten by a raptor"

It's weird if this hasn't been asked before, (Is it common knowledge?) but I couldn't find any. So I'm sorry if it has and I missed it.

like image 991
Şafak Gür Avatar asked Mar 07 '12 10:03

Şafak Gür


People also ask

How do I replace multiples in a string?

Use the replace() method to replace multiple characters in a string, e.g. str. replace(/[. _-]/g, ' ') . The first parameter the method takes is a regular expression that can match multiple characters.

How do you replace two or more characters in a string python?

We can replace multiple characters in a string using replace() , regex. sub(), translate() or for loop in python.

How do you replace multiple values?

Find and replace multiple values with nested SUBSTITUTE The easiest way to find and replace multiple entries in Excel is by using the SUBSTITUTE function. The formula's logic is very simple: you write a few individual functions to replace an old value with a new one.

Which two functions are used for replacing a string with another string?

Replace(String, String, StringComparison) Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string, using the provided comparison type.


1 Answers

So what you need is for the matching process to only take place once. For once I think the right answer is actually 'use regex' ! Here's some code:

var replacements = new Dictionary<string, string>
                       {
                           { "do|g", "cat" },
                           { "ca^t", "mouse" },
                           { "mo$$use", "raptor" }
                       };

var source = "My do|g ate a ca^t which once ate a mo$$use";

var regexPattern = 
    "(" + 
    string.Join("|", replacements.Keys.Select(Regex.Escape)) +
    ")";

var regex = new Regex(regexPattern);

var result = regex.Replace(source, match => replacements[match.Value]);

// Now result == "My cat ate a mouse which once ate a raptor"

The pattern we build here looks like (dog|cat|mouse). Each piece in this alternation construct ( | ) is passed through Regex.Escape, so that regex-meaningful characters in the keys (such as |, ^, etc) don't cause problems. When a match is found, the matching text is replaced by the corresponding value in the dictionary. The string is only scanned once, so there's no repeated matching as is the problem with a iterated string.Replace.

like image 122
AakashM Avatar answered Sep 17 '22 23:09

AakashM