如何避免C#replace通过第二次replace再次替换新字符串

问题描述 投票:0回答:5

假设我想将短语“First Name”和“Name”替换为“#First Name”。

例如:

string text = "first name and name should be with # as prefix and suffix";
text = text.Replace("first name", "#first name#");
text = text.Replace("name", "#name#");
Console.WriteLine(text);
    

我希望输出为:“#first name# 和 #name# 应以 # 作为前缀和后缀”

但是第二个替换也替换了替换的文本,因此短语#first name#中的“name”再次替换:#first #name##和#name#应该以#作为前缀和后缀。

是否有一个选项可以保护以 # 开头和结尾的短语,或者对这两个短语进行“一次”替换?

谢谢。

第一次更换后: “我的全名是我的#名字#和我的姓氏”

c# replace
5个回答
6
投票

使用中间值:

string text = "first name and name should be with # as prefix and suffix";
text = text.Replace("first name", "#SOME_UNIQUE_CODE#");
text = text.Replace("name", "#name#");
text = text.Replace("#SOME_UNIQUE_CODE#", "#first name#");
Console.WriteLine(text);

或者使用正则表达式替换。


3
投票

如果该代码是文字,请使用 string.Format。

string.Format("{0} and {1} should be with # as prefix and suffix", "#first name#", "#name#");

您还可以颠倒顺序并将替换的文本包含在任何重叠的替换中:

string text = "first name and name should be with # as prefix and suffix";
text = text.Replace("name", "#name#");
text = text.Replace("first #name#", "#first name#");
Console.WriteLine(text);

1
投票
Regex.Replace(input, "(first\ name|name)", match => {
 if (match.Value == "name") return "#name#";
 else if (match.Value == "first name") return "#first name#";
 else throw new InvalidOperationException("bug");
});

使用正则表达式一次匹配所有可能的字符串,然后在匹配评估器中决定替换什么。这种方法具有很强的可扩展性,而不是 hack。


0
投票

您可以使用仅替换出现的

name
的正则表达式,而在其前面或后面没有
#

string text = "first name and name should be with # as prefix and suffix";
text = text.Replace("first name", "#first name#");
text = Regex.Replace(text, @"([^\#])(name)([^\#])", "$1#$2#$3");
Console.WriteLine(text);

输出:

#first name# and #name# should be with # as prefix and suffix

-3
投票

使用正则表达式..这是一个 ruby 片段。翻译成 C# 应该很简单

> puts str.gsub( /(first\s)?name/ , "#\\0#") 

=> #first name# and #name# should be with # as prefix and suffix
© www.soinside.com 2019 - 2024. All rights reserved.