簡體   English   中英

c#用包含未知部分的替換字符串

[英]c# Replace string with does contains unknown parts

我有一個包含文本的文件。 現在,我必須用另一個替換一些字符串。 例如,我必須更換

"[ContactLetterSalutation]" 

 "Dear Thomas Kehl". 

現在,占位符"[ContactLetterSalutation]"包含某個地方"=\\r\\n" - 這可能是一次,兩次或更多次 - 例如

"[Conta=\r\ntLetterSa=\r\nlutation]".

我現在正在尋找一種方式,我也可以替換它 - 我不知道會在哪里和有多少次"=\\r\\n" 困難的是,我不應該在文本中替換所有出現的"=\\r\\n" 有人可以幫我怎么做? 是否有可能使用RegEx執行此操作?

謝謝。 最誠摯的問候,托馬斯

  • 使用正則表達式搜索括號內的任何內容。
  • 對於每個匹配,請刪除所有= \\ r \\ n以查找密鑰。
  • 將匹配替換為值。

例:

  • 你搜索[ 任何 ]
  • 你找到[Conta=\\r\\ntLetterSa=\\r\\nlutation]
  • 您使用密鑰ContatLetterSalutation來查找正確的值。
  • 用該值替換[Conta=\\r\\ntLetterSa=\\r\\nlutation]
string GetReplacement(Match m) {
    // Get the matched string.
    string x = m.ToString().Replace("=\r\n","");
    return Lookup[x];
}

...
file = Regex.Replace(file, @"\[.*?\]", GetReplacement, RegexOptions.Singleline);
編輯:

RegexOptions.Singleline導致。 匹配\\ n

EDIT2:

雖然以上內容適用於小文件,但我認為這個問題對於無法將整個文件放入單個字符串的流更有趣。 我想出了這個,但它可能有錯誤:

 static IEnumerable<string> Chunk(TextReader reader) { char[] chars = new char[MaxBufferSize]; string buffer = ""; int charsRead; while ((charsRead = reader.ReadBlock(chars, 0, MaxBufferSize)) > 0) { buffer = buffer + new string(chars,0,charsRead); int indexOfOpenBracket; if((indexOfOpenBracket = buffer.IndexOf('[')) == -1) { if (!string.IsNullOrEmpty(buffer)) yield return buffer; buffer = ""; continue; } while (indexOfOpenBracket!=-1) { string outsideBrackets = buffer.Substring(0, indexOfOpenBracket); if(!string.IsNullOrEmpty(outsideBrackets)) yield return outsideBrackets; buffer = buffer.Substring(indexOfOpenBracket + 1); int indexOfCloseBracket = buffer.IndexOf(']'); if (indexOfCloseBracket != -1) { string insideBrackets = buffer.Substring(0, indexOfCloseBracket); buffer = buffer.Substring(indexOfCloseBracket + 1); yield return DoLookup(insideBrackets); } else { buffer = '[' + buffer; break; } indexOfOpenBracket = buffer.IndexOf('['); } } yield return buffer; } public static void BufferReplace(Stream input, Stream output) { StreamReader reader = new StreamReader(input); StreamWriter writer = new StreamWriter(output); foreach (var chunk in Chunk(reader)) { writer.Write(chunk); } writer.Flush(); } 

是的,你可以用正則表達式做到這一點。 我不會試圖在一次通過中實現這一點。 我假設您有一個HashTable或其他存儲,您可以在其中查找占位符字符串以獲取要放在其中的文本。 另外我假設您想要從C#代碼執行此操作,有一個工具調用sed,它將從unix / linux或cygwin underwindows中的命令行執行此操作。 它適用於正則表達式。

在制作正則表達式時,我喜歡使用這個網站: http//regexpal.com/

所以首先你嘗試找到占位符中帶有不需要的\\ r \\ n的模式:“\\ [([^ \\]] +)\\]”這將找到任何以[至少有一個]開頭的模式不是]並以]結尾的字符。

獲得匹配列表后,您可以在將其用於查找之前刪除不需要的模式。

這是一個非常簡單的小例子:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            String textFromFile = "some text [re=\r\npla=\r\nme] more [Anoth=\r\ner=\r\n place=\r\n=\r\n=\r\n holder] text";

            foreach (Match match in Regex.Matches(textFromFile, "\\[([^\\]]+)\\]"))
            {
                String placeHolder = match.Groups[1].Value.Replace("=\r\n", "");
                // *** Do rest of your work here ***.
                System.Console.WriteLine(placeHolder);
            }
        }
    }
}

該程序打印出來:

replaceme
Another place holder

暫無
暫無

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

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