簡體   English   中英

正則表達式首先匹配,然后替換找到的匹配項

[英]Regex to first match, then replace found matches

在我的C#程序中,我使用正則表達式執行以下操作:

  • 循環瀏覽需要替換的單詞列表。
  • 對於每個單詞,找出給定的字符串是否有匹配項。
  • 如果是這樣,我將執行一些(略微昂貴的)邏輯來創建替換項。
  • 然后執行實際更換。

我當前的代碼大致如下:

string toSearchInside; // The actual string I'm going to be replacing within
List<string> searchStrings; // The list of words to look for via regex

string pattern = @"([:@?]{0})";
string replacement;

foreach (string toMatch in searchStrings)
{
    var regex = new Regex(
                            string.Format(pattern, toMatch), 
                            RegexOptions.IgnoreCase
                            );
    var matches = regex.Matches(toSearchInside);

    if (matches.Count == 0)
        continue;

    replacement = CreateReplacement(toMatch);

    toSearchInside = regex.Replace(toSearchInside, replacement);

我可以使它正常工作,但是它似乎效率不高,因為它兩次使用了regex引擎-一次找到匹配項( regex.Matches() ),一次查找替換的regex.Replace() )。 我想知道是否有辦法簡單地說替換您已經找到的比賽

您可以從第一個匹配項中獲得所有匹配項-並且對於每個匹配項都有其索引,您可以遍歷匹配項並將其替換為字符串本身-因為它比regex替換更有效。

盡管我可以通過小型單元測試來衡量性能(並且在后台運行NCrunch可以使其運行更快)

暫無
暫無

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

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