簡體   English   中英

使用正則表達式替換的特殊符號

[英]Special signs with Regex Replace

我想用正則表達式替換字符串,但我不能替換正則表達式特殊符號 - 我只想將正則表達式讀取^等作為普通字符串而不是特殊符號。 我試過\\\\但它仍然無法正常工作。

public static string ReplaceXmlEntity(string source)
{
    if (string.IsNullOrEmpty(source)) return source;
    var xmlEntityReplacements = new Dictionary<string, string>
    {
        // Find all the original spaces and replace with a space
        // and placemarker for the space
        {" ", " ^"},
        {" \\^ \\^", " ^"},
        // Find all the double quotes and replace with placemarker 
        {"''", " ~ "},
        // Add extra spaces around key values so they can be isolated in
        // into their own array slots
        {",", " , "},
        {"'", " ' " },
        {"'('", " ( " },
        {"')'", " ) " },
        // Replace all the special characters and extra spaces
        {"\n", " 0x000A " },
        {"\r", " 0x000D " },
        {"\t", " 0x0009 " },
        {"\v", " 0x000B " },
    };
    return Regex.Replace(source, string.Join("|", xmlEntityReplacements.Keys
        .Select(k => k.ToString()).ToArray()), m => xmlEntityReplacements[m.Value]);
}

當您對字典鍵中的特殊字符進行轉義時,除非您對匹配項進行轉義,否則您將無法再訪問它們,但這可能會導致其他問題。 這意味着您應該使用Regex.Escape分別轉義每個字典鍵:

xmlEntityReplacements.Keys.Select(k => Regex.Escape(k.ToString()))

您不需要.ToArraystring.Join接受IEnumerable

暫無
暫無

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

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