簡體   English   中英

正則表達式替換包含一個子字符串但不包含另一個子字符串的字符串

[英]Regex replace in a string that contains one substring and does not contain another substring

我有一個看起來像這樣的文本:

[customer id = "1" name="Bob" ...]
[customer id="2" name="Adam" ...]
[customer id="3" ...]
[customer id = "4" name="Julia" ...]

我有一個函數,如果未指定Name,則應將Name添加到條目:

string AddNameIfDoesNotSpecified(string text, string id, string name)
{
    return Regex.Replace(text,
                    $"id\\s*=\\s*\"{id}\"",
                    $"id=\"{id}\" name=\"{name}\"",
                    RegexOptions.IgnoreCase | RegexOptions.Compiled);
}

除了可以替換,即使指定了名稱也可以。 如何更改正則表達式以檢查是否存在"name\\\\s*="子字符串,以及是否存在-不進行替換?

我需要實現的另一件事是UpdatName方法:

string UpdateNameIfSpecified(string text, string id, string oldName, string newName)
{
    return Regex.Replace(text,
                    $"id\\s*=\\s*\"{id}\" name\\s*=\\s*\"{oldName}\"",
                    $"id=\"{id}\" name=\"{newName}\"",
                    RegexOptions.IgnoreCase | RegexOptions.Compiled);
}

它可以工作,但是如果我們在idname之間還有其他屬性,例如:

[customer id="5" gender="female" name="Marta" ...]

它不起作用,如何使用正則表達式在C#中使其起作用? 我應該使用小組嗎?

例子:

AddNameIfDoesNotSpecified("[customer id = \"6\" ...]", "6", "Alex") 
               // output: "[customer id=\"6\" name=\"Alex\" ...]"

AddNameIfDoesNotSpecified("[customer id =\"7\" gender=\"male\" name=\"Greg\" ...]", "7", "Eric") 
               // output: "[customer id=\"7\" gender=\"male\" name=\"Greg\" ...]"

UpdateNameIfSpecified("[customer id = \"8\" ...]", "8", "Sam", "Don") 
           // output: "[customer id=\"8\" ...]"

UpdateNameIfSpecified("[customer id = \"9\" name=\"Lisa\" ...]", "9", "Lisa", "Carl") 
           // output: "[customer id=\"9\" name=\"Carl\" ...]"

UpdateNameIfSpecified("[customer id=\"10\" gender=\"female\" name=\"Megan\" ...]", "10", "Megan", "Amy") 
           // output: "[customer id=\"10\" gender=\"female\" name=\"Amy\" ...]"

UpdateNameIfSpecified("[customer id = \"11\" name=\"Tim\" ...]", "11", "Timothy", "Andrew") 
           // output: "[customer id=\"11\" name=\"Tim\" ...]"

對於第一個,使用先行斷言

   $"id\\s*=\\s*\"{id}\"(?!.*?name\\s*=)",
   $"id=\"{id}\" name=\"{name}\" ",

對於第二個,使用捕獲組

   $"id\\s*=\\s*\"{id}\"(.*?)name\\s*=\\s*\"{oldName}\"",
   $"id=\"{id}\"$1name=\"{newName}\"",

構造時檢查這些字符串看起來像正則表達式。

另外,請注意\\s將跨越換行符
(使用[^\\S\\r\\n]可以避免這種情況)

.*? 不會跨越換行符(如果需要,請使用全點修飾符)。

暫無
暫無

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

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