有一种方法
Regex.Replace(string source, string pattern, string replacement)最后一个参数支持模式替换,如${groupName}等(但我不知道运行时的组名)。
在我的例子中,我有动态创建的模式,如下所示:
(?<c0>word1)|(?<c1>word2)|(?<c2>word3)我的目的是将每个组替换为取决于组名的值。例如,单词"word1“将替换为<span class="c0">word1</span>。这是为了像google一样突出显示搜索结果。
有没有可能使用上面的方法,而不是使用带有MatchEvaluator参数的重载方法?
提前感谢!
发布于 2009-07-12 08:47:20
我不认为以您建议的方式使用${groupname}是可行的,除非我误解了正在执行的确切替换。原因是替换字符串的构造方式必须考虑到每个组名。因为它们是动态生成的,所以这不可能实现。换句话说,如何在一条语句中设计一个替换字符串来覆盖c0...cn并替换它们各自的捕获值?您可以遍历名称,但如何保持修改后的文本完好无损,以便对每个组名执行1次替换?
不过,我确实有一个可行的解决方案。它仍然使用MatchEvaluator重载,但使用一些lambda表达式和LINQ,您可以将其减少到1行。但是,为了清楚起见,我将在下面对其进行格式化。也许这将满足您的需求,或者为您指明正确的方向。
string text = @"The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.";
string[] searchKeywords = { "quick", "fox", "lazy" };
// build pattern based on keywords - you probably had a routine in place for this
var patternQuery = searchKeywords
.Select((s, i) =>
String.Format("(?<c{0}>{1})", i, s) +
(i < searchKeywords.Length - 1 ? "|" : ""))
.Distinct();
string pattern = String.Join("", patternQuery.ToArray());
Console.WriteLine("Dynamic pattern: {0}\n", pattern);
// use RegexOptions.IgnoreCase for case-insensitve search
Regex rx = new Regex(pattern);
// Notes:
// - Skip(1): used to ignore first groupname of 0 (entire match)
// - The idea is to use the groupname and its corresponding match. The Where
// clause matches the pair up correctly based on the current match value
// and returns the appropriate groupname
string result = rx.Replace(text, m => String.Format(@"<span class=""{0}"">{1}</span>",
rx.GetGroupNames()
.Skip(1)
.Where(g => m.Value == m.Groups[rx.GroupNumberFromName(g)].Value)
.Single(),
m.Value));
Console.WriteLine("Original Text: {0}\n", text);
Console.WriteLine("Result: {0}", result);输出:
Dynamic pattern: (?<c0>quick)|(?<c1>fox)|(?<c2>lazy)
Original Text: The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.
Result: The <span class="c0">quick</span> brown <span class="c1">fox</span> jumps over the <span class="c2">lazy</span> dog. The <span class="c0">quick</span> brown <span class="c1">fox</span> jumps over the <span class="c2">lazy</span> dog.https://stackoverflow.com/questions/1099439
复制相似问题