4

I'm new in programming and need some help ;-) how can I replace multiple patterns in a string?

Example:

static void Main(string[] args)
{
  string input = "this is a test AAA one more test adakljd jaklsdj BBB sakldjasdkj CCC";
  string [] pattern = {"AAA", "BBB","CCC"};
  string replacement = "XXX";

  string result = null;
  for (int i = 0; i < pattern.Length; i++)
  {
    result = Regex.Replace(input, pattern[i], replacement);
  }

  Console.WriteLine(result);
}

Want the result:

this is a test XXX one more test adakljd jaklsdj XXX sakldjasdkj XXX

But I get:

this is a test AAA one more test adakljd jaklsdj BBB sakldjasdkj XXX

thx for help in advance!

3 Answers 3

1

You don't need a regex, you simply can use Replace:

string input = "this is a test AAA one more test adakljd jaklsdj BBB sakldjasdkj CCC";
string replaced = input.Replace("AAA", "XXX").Replace("BBB", "XXX")...
Sign up to request clarification or add additional context in comments.

1 Comment

I'd imagine AAA etc are placeholders for what could be more intricate regex
1

I suggest combining all patterns' parts ("AAA", ..., "CCC") with | ("or"):

  string input = "this is a test AAA one more test adakljd jaklsdj BBB sakldjasdkj CCC";
  string[] pattern = { "AAA", "BBB", "CCC" };
  string replacement = "XXX";

  string result = Regex.Replace(
    input, 
    string.Join("|", pattern.Select(item => $"(?:{item})")), 
    replacement);

  Console.WriteLine(result);

Outcome:

this is a test XXX one more test adakljd jaklsdj XXX sakldjasdkj XXX 

I've turned each pattern part like BBB into a group (?:BBB) in case pattern part contains | within itself

Comments

0

You're overwriting the result variable throughout the loop repeatedly, there doesn't seem to be any need for it either, just use the input variable

input = Regex.Replace(input, pattern[i], replacement);
...
Console.WriteLine(input);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.