簡體   English   中英

使用 C# 和正則表達式在字符串列表中查找整個單詞,然后僅替換該單詞

[英]Using C# and regex to find a whole word in a list of strings, and then replacing only that word

美好的一天人們...我需要找到一種方法,使用 c# 和正則表達式表達式,首先,在字符串列表中找到一個單詞,我們稱之為搜索。 字符串列表示例:我有很多字符串列表列表;這只是一個包含 4 個字符串的列表:

 {"   port MegaModuleRefitLogEventMegaModuleRefitLogEvent.REFIT_FINISHED,moduleId,id,ActionJSON.encodeJSONanalyticExport,ActionJSON.encodeJSON_pendingDesign.analyticExport,ActionJSON.port.encodeJSON_pendingDesign.analyticExportthis;",

    "private static var _warReportManager:WarReportManager = new WarReportManager.port;",
"import com.waterworld.managers.warreport.WarReportManager;",
"else iflastBattleReport.report != port && lastBattleReport.port"}

現在,我的搜索首先是“端口”,我使用了:

string search="port"
if (myStrList.Any(str => str.Contains(search)))
{
//go to the funtion that does the actual replacing etc
}

找到它...tho,我的表達式找到包含搜索的所有列表...包括無效場景...

這個給定的列表在示例中包含 4 個字符串……所有 5 個字符串都以各種形式出現了不止一次的“端口”。 我的字符串列表有時會出現很多次,有時沒有...但它是一個列表。 我需要用上面的表達式找到可接受的事件:在列表的第一個字符串上:

  1. “ port ”開頭沒有空格是有效的;

  2. “。港口。” 沒有“。” 已驗證...”。” 可以是 .",:'[]{}<>;

  3. 第一個字符串中的所有其他出現都無效。

在列表的第二個字符串上: - - ".port;" 沒有“.”也是有效的和 ”;”

在第三個字符串上:

  • 沒有有效的事件。

在第四個字符串上:

  1. “!= 端口 &&” 在沒有“!=”和“ &&”的情況下有效
  2. “.port”是有效的...沒有“.”並且最后一個字符可能為空。

然后一旦我找到包含搜索的有效字符串......我需要用它們做一些功能......其中一個是用“myport”注釋替換給定的單詞say..所有搜索//替換是區分大小寫的。

string pattern = @"\b"+search+@"\b";
string replace = "myport";
string result = Regex.Replace(input, pattern, replace);

tho,這只適用於邊界為空白的那些……而不是其他場景……任何幫助都會受到重視。 我環顧四周,這些全詞場景中的大部分都是特定於空白的,不過……這里可能有我的情況的答案……問候

編輯。 感謝@jdweng

對於搜索我做了如下:

string pattern = string.Format(@"[\s]+{0}[\s.!?$]+", search);

                            Regex matcher = new Regex(pattern);

                            if (teslist.Any(str => matcher.IsMatch(str)))
                            {
                                Console.WriteLine("string match found: "");
                            }

編輯 2 ...... tho jdweng 的答案很接近......它不是所需的結果......我試圖將要求如下:搜索模式:

  • 可以在空格之后開始,
  • 可以在這些字符之后開始,.<>;:'"{}[]\\?/-_+=()
  • 可能在行首
  • 必須只包含搜索字符串
  • 可能不是帶有字母數字的單詞開頭的一部分
  • 可能不是詞尾部分的一部分
  • 可能在空白之前結束,
  • 可能在 ,.<>;:'"{}[]\\?/-_+=() 之前結束
  • 可能在行尾

jdweng 的回答並沒有包含所有選項......而且......它替換了搜索,包括那些開始或結束字符,其中,我只需要替換給定的搜索字符串。

下面的代碼有效。 我替換了 \\b 以獲得任何空白。 並用加號放入方括號以獲得多次出現。 最后做了類似的並包括句號、感嘆號和問號,這些都可能出現在句子末尾:

        {
            string[] inputs = {
                                  "   port MegaModuleRefitLogEventMegaModuleRefitLogEvent.REFIT_FINISHED,moduleId,id,ActionJSON.encodeJSONanalyticExport,ActionJSON.encodeJSON_pendingDesign.analyticExport,ActionJSON.port.encodeJSON_pendingDesign.analyticExportthis;",
                                  "private static var _warReportManager:WarReportManager = new WarReportManager.port;",
                                  "import com.waterworld.managers.warreport.WarReportManager;",
                                  "else iflastBattleReport.report != port && lastBattleReport.port"};

            string findWord = "port";
            string pattern = string.Format("(?'prefix'[\\s.]+)(?'word'{0})((?'suffix'[\\s.!?;]+)|(?'suffix'$))", findWord);

            string replace = "myport";
            string replacePattern = string.Format("${{prefix}}{0}${{suffix}}", replace);

            foreach (string input in inputs)
            {
                string result = Regex.Replace(input, pattern, replacePattern);
                Console.WriteLine(result);
            }
            Console.ReadLine();

好的..首先,為了過濾可能的 matchc 列表......看看列表中是否有匹配......我做了:

string pattern = string.Format(@"[\W\s\b]{0}[\b\s\W]", search);

Regex matcher = new Regex(pattern);

if (teslist.Any(sTrr => matcher.IsMatch(sTrr)))
 {
      Console.WriteLine("search found for list");
        //....do stuff
     }

然后..在替換部分..我必須在模式上創建一個正則表達式匹配列表,並分別替換每個匹配...

string pattern = string.Format(@"[\W\s\b]{0}[\b\s\W]", search);
    Regex ItemRegex = new Regex(pattern, RegexOptions.Compiled);
    List<KeyValuePair<string,string>> MatchList = new List<KeyValuePair<string,string>>();
    foreach (Match ItemMatch in ItemRegex.Matches(str))
         {
            string myMatch = ItemMatch.ToString();
            string myReplace = (ItemMatch.ToString().Replace(read, replace));
            KeyValuePair<string, string> ThisPair = new KeyValuePair<string, string>(myMatch, myReplace);
            MatchList.Add(ThisPair);
          }
     string newValue = str;
     foreach (KeyValuePair<string,string> KVstr in MatchList)
           {
               newValue = (str.Replace(KVstr.Key, KVstr.Value));
            }
     Console.WriteLine("str: " + str);
     Console.WriteLine(" newValue: " + newValue);

暫無
暫無

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

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