替换"标签"使用字典值,哪个键是标记

时间:2014-09-16 10:10:09

标签: c# regex dictionary

假设我有一个以下形式的词典:

"NUM" : "1"
"TEXT" : "abc"

和一个字符串:"This pair contains {NUM} and {TEXT}"

如何使用我的词典中的相应值替换{NUM}{TEXT}

这是我现在的代码:

Regex.Replace(myString, // "This pair contains {NUM} and {TEXT}"
    @"{([\w\s]*)}", // Gets any word or space character between braces
    myDictionary[@"$1"]) // Does not work, it literally searches for "$1" instead of the match

1 个答案:

答案 0 :(得分:3)

您需要使用匹配评估程序。

正则表达式

@"{([\w\s]*)}"

代码

var result = Regex.Replace(myString, // "This pair contains {NUM} and {TEXT}"
    @"{([\w\s]*)}", // Gets any word or space character between braces
    m => myDictionary.ContainsKey(m.Groups[1].Value)
         ? myDictionary[m.Groups[1].Value]  // to be safe do the checking
         : string.Empty);

输出

This pair contains 1 and abc

DEMO