我有一个这样的字符串:
string s = "<p>Hello world, hello world</p>";
string[] terms = new string[] {"hello", "world"};
我想对此字符串进行替换,以便匹配每个单词(不区分大小写),并替换为带编号的索引span标记,如下所示:
<p>
<span id="m_1">Hello</span>
<span id="m_2">world</span>,
<span id="m_3">hello</span>
<span id="m_4">world</span>!
</p>
我试过这样做。
int match = 1;
Regex.Replace(s,
String.Join("|", String.Join("|", terms.OrderByDescending(s => s.Length)
.Select(Regex.Escape))),
String.Format("<span id=\"m_{0}\">$&</span>", match++),
RegexOptions.IgnoreCase);
输出是这样的:
<p>
<span id="m_1">Hello</span>
<span id="m_1">world</span>,
<span id="m_1">hello</span>
<span id="m_1">world</span>!
</p>
其中所有ID都相同(m_1),因为正则表达式不会为每个匹配评估匹配++,而是针对整个正则表达式进行评估。我该如何解决这个问题?
答案 0 :(得分:5)
您需要做的就是将替换参数从字符串模式转换为匹配评估程序(m => String.Format("<span id=\"m_{0}\">{1}</span>", match++, m.Value)
):
string s1 = "<p>Hello world, hello world</p>";
string[] terms = new string[] {"hello", "world"};
var match = 1;
s1 = Regex.Replace(s1,
String.Join("|", String.Join("|", terms.OrderByDescending(s => s.Length)
.Select(Regex.Escape))),
m => String.Format("<span id=\"m_{0}\">{1}</span>", match++, m.Value),
RegexOptions.IgnoreCase);
Console.Write(s1);
// => <p><span id="m_1">Hello</span> <span id="m_2">world</span>, <span id="m_3">hello</span> <span id="m_4">world</span></p>
请参阅C# demo