如何将两个或多个字符串相互替换? [英] How to replace two or more strings with each other?

查看:49
本文介绍了如何将两个或多个字符串相互替换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用 C# 将字符串的某些部分相互替换.我只能找到一个关于如何实现这一目标的类似问题 在这里但它是PHP.

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.

我的情况涉及一个包含要替换的对的 Dictionary[string, string] :

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

  • 狗,猫
  • 猫,老鼠,
  • 老鼠,猛禽

我有一个字符串,其值为:

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"

如果我枚举字典并调用 string.Replace 按顺序,我会得到这个:

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.

推荐答案

所以你需要的是匹配过程只发生一次.这一次我认为正确的答案实际上是使用正则表达式"!这是一些代码:

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"

我们在这里构建的模式看起来像 (dog|cat|mouse).在这个交替构造 ( | ) 中的每一部分都通过 Regex.Escape 传递,以便键中的正则表达式有意义的字符(例如 |^ 等)不会引起问题.当找到匹配项时,匹配的文本将替换为字典中的相应值.字符串只扫描一次,所以没有重复匹配,因为迭代 string.Replace 存在问题.

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.

这篇关于如何将两个或多个字符串相互替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆