C#正则表达式替换或重叠匹配短语

时间:2017-04-13 18:38:23

标签: c# regex

我有一些类似的文字:

#include <iostream>
#include <fstream>

我想做一个C#正则表达式来突出显示数组中的单词:

string[] words = new string[] { "Billy", "Billy Jr.", "party" };
string s = "<p>Billy and Billy Jr. are both coming to the party.</p>";

我尝试使用foreach循环:

string s = "<p><span>Billy</span> and <span>Billy Jr.</span> are both coming to the <span>party</span>.";

但问题是,当我做Billy时,它会在Billy Jr.上匹配,那个短语会被包裹两次。我如何实现我想要的目标?

1 个答案:

答案 0 :(得分:0)

不是循环和执行三次正则表达式,而是可以制作一个将逐渐匹配的正则表达式:

(Billy Jr\.|Billy|party)

如果你使用它,它会在Billy Jr.之前匹配Billy,所以如果找到第一个,它将只替换那个。

regex101 proof

无耻地窃取juharr s comment(这就是我上面写的),你可以用C#来做:

s = Regex.Replace
    ( s
    , string.Join
      ( "|"
      , words.OrderByDescending(s => s.Length)
             .Select(Regex.Escape)
      , "<span>$&</span>"
      , RegexOptions.IgnoreCase
    );

它的作用:它根据单词数组创建一个正则表达式。它首先对阵列进行最长的排序,以防止“比利”问题。然后它会在每个单词上调用Regex.Escape以逃避.。然后它使用生成的正则表达式来进行替换。