C#Regex替换类似的单词

时间:2017-01-31 18:59:43

标签: c# regex replace

需要在以下表达式中替换名为[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.

2 个答案:

答案 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

请参阅:https://regex101.com/r/2uTCjD/1

测试它:http://ideone.com/01Yxng

答案 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"