需要在以下表达式中替换名为[WORD, WORD1, WORD2,..., WORDnnn]
的操作数:
WORD-WORD1+WORD11
操作数命名为:
[WORD_NEW, WORD1_NEW, WORD2_NEW, WORDnnn_NEW]
某些操作数未映射,不应替换它们。
WORD-WORD1+WORD11 => WORD_NEW-WORD1_NEW+WORD11_NEW
WORD-WORD1+WORD11 => WORD_NEW-WORD1_NEW+WORD11 if WORD11 is not mapped.
答案 0 :(得分:0)
这应该有效。
正则表达式:
(WORD\d*)
替换为:
$1_NEW
C#代码:
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"(WORD\d*)";
string substitution = @"$1_NEW";
string input = @"WORD, WORD1, WORD2";
RegexOptions options = RegexOptions.Multiline;
Regex regex = new Regex(pattern, options);
string result = regex.Replace(input, substitution);
Console.WriteLine(result);
}
}
输出:
WORD_NEW, WORD1_NEW, WORD2_NEW
答案 1 :(得分:0)
由于你已经拥有了地图(可能是Dictionary<string,string>
的形式),只需运行Replace
,它接受委托并检查每个特定匹配是否存在映射:
var mapping = new Dictionary<string,string>{{"WORD1", "WORD_NEW1"}};
var result = Regex.Replace("WORD-WORD1+WORD11", "WORD\d+",
match => mapping.ContainsKey(match.Value)? mapping[match.Value] : match.Value);
// result is "WORD-WORD_NEW1+WORD11"