繁体   English   中英

使用Regex.Replace()代替string.Replace()

[英]Using Regex.Replace() instead of string.Replace()

我有一个Dictionary<string , string> dict和一个string script 我想用字典中的相应value替换script每次出现的key ,只替换与键相同的标记。

字典dict具有以下条目:

"name" : "John"
"age"  : "34"

string script = " The name and the fathersname and age and age_of_father "

替换后的输出应为:

script = " The John and the fathersname and 34 and the age_of_father " 

我试过使用string.Replace()但它不起作用。 如何使用Regex.Replace()和Lookahead的概念来完成此操作?

让我们匹配每个单词\\w+最简单的模式:单词是一个或多个unicode单词字符的序列),并检查(借助词典)是否应该替换它:

Dictionary<string, string> dict = 
  new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) {
    { "name", "John"},
    { "age", "34"}
  };

string script = " The name and the fathersname and age and age_of_father ";

//  The John and the fathersname and 34 and age_of_father 
string result = Regex.Replace(
  script,
 @"\w+",   // match each word
  match => dict.TryGetValue(match.Value, out var value) // should the word be replaced? 
    ? value          // yes, replace
    : match.Value);  // no, keep as it is

在您的问题中“无效”是什么意思? 你在看什么 您的代码是什么样的?

请记住,字符串是不可变的,并且string.Replace不会更改原始字符串,它会返回更改后的新字符串。

对于这样的事情(在进行大量替换时循环),StringBuilder.Replace通常是一个更好的选择。 StringBuilder实例是可变的,因此StringBuilder.Replace可以就地执行其工作。

请执行下列操作:

  • 使用脚本字符串初始化StringBuilder
  • 循环遍历词典进行替换
  • 完成后,在StringBuilder上调用ToString以获取结果

我希望有一种方法可以使StringBuilder和Regex一起工作。

暂无
暂无

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

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