简体   繁体   English

正则表达式替换多个模式

[英]regex replace multiple patterns

I'm new in programming and need some help ;-) how can I replace multiple patterns in a string ? 我是编程新手,需要一些帮助;-)如何替换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 这是一个测试XXX一个测试adakljd jaklsdj XXX sakldjasdkj XXX

But I get: 但我得到:

this is a test AAA one more test adakljd jaklsdj BBB sakldjasdkj XXX 这是测试AAA的另一个测试adakljd jaklsdj BBB sakldjasdkj XXX

thx for help in advance! thx提前帮助!

You don't need a regex, you simply can use Replace : 你不需要正则表达式,你只需使用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")...

I suggest combining all patterns' parts ( "AAA", ..., "CCC" ) with | 我建议所有模式的部分( "AAA", ..., "CCC" )与|组合 ("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 | 在模式部分包含|情况下,我将每个模式部分像BBB一样变成一个 (?:BBB) within itself 在其内部

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 你在整个循环中重复覆盖result变量,似乎也没有任何需要,只需使用input变量

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM