簡體   English   中英

正則表達式:命名組和替換

[英]Regex: Named groups and replacements

有一種方法

Regex.Replace(string source, string pattern, string replacement)

最后一個參數支持模式替換,例如${groupName}和其他(但我不知道運行時中的組名)。

在我的情況下,我有動態創建的模式,如:

(?<c0>word1)|(?<c1>word2)|(?<c2>word3)

我的目的是使用取決於組名的值替換每個組。 例如,單詞“word1”將替換為<span class="c0">word1</span> 這是針對像谷歌一樣突出顯示的搜索結果。

是否可以使用上述方法不使用帶有MatchEvaluator參數的重載方法來執行此操作?

提前致謝!

我不認為以你建議的方式使用$ {groupname}是可行的,除非我誤解了正在執行的確切替換。 原因是替換字符串必須以這樣的方式構造,即它考慮每個組名。 由於它們是動態生成的,因此無法實現。 換句話說,在1語句中,您是如何設計一個替代字符串來覆蓋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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM