簡體   English   中英

C# 使用正則表達式和字典替換“僅整個單詞”

[英]C# Replace "Whole words only" using RegEx and dictionary

我想創建代碼,替換一個文件中包含的單詞,使用另一個文本文件作為字典(結構。:Key sep.:tab Value)。

當前代碼:

var fileDictionary = new Dictionary<string, string>
   File.ReadLines(dictionaryPath, Encoding.Default)
  .Select(line => line.Split('  '))
  .ToDictionary(data => data[0], data => data[1]), StringComparer.InvariantCultureIgnoreCase);//create dictionary based on text file

for (int i = 0; i < rowNumber; i++)
{
   var output = fileString[i].ToString();// current row, taked from other file
   var replaced = Regex.Replace(output, String.Join("|", fileDictionary.Keys.Select(Regex.Escape)), m => fileDictionary[m.Value], RegexOptions.IgnoreCase);
   var result = replaced.ToString();
   outputFile += result.ToString();
   outputFile += "\r\n";
}

到目前為止,一切正常,我正在使用 RegEx 替換字典中收集的單詞,但是我在替換“僅整個單詞”類型時遇到問題。

我決定使用像 @"\\bsomeword\\b" 這樣的模式,但是當我按照下面的描述實現它時:

 var replaced = Regex.Replace(output, String.Join("|", 
         String.Format(@"\b{0}\b", 
         fileDictionary.Keys.Select(Regex.Escape))), 
         m => fileDictionary[m.Value], RegexOptions.IgnoreCase);

該代碼不返回任何結果。 最終文本文件看起來像原始文件。 沒發生什么事。 我意識到,問題出在字典鍵上,當我使用模式時,我實際上更改了鍵,而當前字典中不存在新鍵。 因此,如果鍵不存在,則不會替換該值。

有沒有人有任何建議如何解決這個問題? 或者也許有人知道使用正則表達式和字典僅替換整個單詞的其他方法?

看起來模式沒有從字典中正確解析

 var replaced = Regex.Replace(fileString, String.Join("|", fileDictionary.Select(m => @"\b" + Regex.Escape(m.Key) + @"\b")), m => fileDictionary[m.Value], RegexOptions.IgnoreCase);

為您的輸出使用 StringBuilder 也會更有效。

暫無
暫無

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

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