我需要編寫帶自定義通配符支持的字符串替換函數。我也應該能夠逃脫這些通配符。我目前有一個帶有Usage,Value和Escape屬性的通配符類。支持自定義通配符並在C#中轉義這些通配符的字符串替換函數
那麼,假設我有一個全局列表通配符。通配符只有一個成員在這裏添加:
Wildcards.Add(new Wildcard
{
Usage = @"\Break",
Value = Enviorement.NewLine,
Escape = @"\\Break"
});
所以我需要一個CustomReplace方法來完成這個技巧。我應該使用另一個字符串替換給定字符串中的指定參數,就像string.Replace
一樣。唯一的區別是它必須使用我的自定義通配符。
string test = CustomReplace("Hi there! What's up?", "! ", "!\\Break");
// Value of the test variable should be: "Hi there!\r\nWhat's up?"
// Because \Break is specified in a custom wildcard in Wildcards
// But if I use the value of the wildcard's Escape member,
// it should be replaced with the value of Usage member.
test = CustomReplace("Hi there! What's up?", "! ", "!\\\\Break");
// Value of the test variable should be: "Hi there!\\BreakWhat's up?"
我當前的方法不支持轉義字符串。 當我調用string的時候,它在性能方面也不會很好。我猜,兩次更換並且每個都搜索整個字符串。
// My current method. Has no support for escape strings.
CustomReplace(string text, string oldValue, string newValue)
{
string done = text.Replace(oldValue, newValue);
foreach (Wildcard wildcard in Wildcards)
{
// Doing this:
// done = done.Replace(wildcard.Escape, wildcard.Usage);
// ...would cause trouble when Escape contains Usage.
done = done.Replace(wildcard.Usage, wildcard.Value);
}
return done;
}
所以,我必須寫一個替代方法,該方法通過字符搜索字符串字符用邏輯來查找和單獨的使用情況與逃生值,然後使用替代逃生而用另一個給定的字符串替換使用?
或者你知道一個已經寫好的嗎?
我可以在這個場景中使用正則表達式嗎?
如果我可以,怎麼樣? (有沒有這方面的經驗,一個模式會很好)
如果我這樣做,它會比字符搜索更快或更慢?
對不起,對於這篇較長的文章,我儘量保持清楚,並對任何錯別字等都感到抱歉;這不是我的主要語言。提前致謝。
你想在自定義函數中使用正則表達式,你可以通過從頭開始使用正則表達式來避免使用正則表達式?這不是破壞了目標嗎? – musefan 2012-03-06 13:02:50
我不懂正則表達式。我的目標是在替換函數中使用自定義通配符,同時能夠轉義它們。如果正則表達式是一種方式,或者是一種比替代方式更好的方法,那麼我會使用它。我的問題是「最佳方式是什麼?」如果它是正則表達式「如何使用正則表達式來做到這一點?」因爲我沒有使用正則表達式的經驗。 – 2012-03-06 14:08:17