我有一個問題,我想在某些文本中用「{{de | < text>}}」替換每個「[[:de:< text>]]」。我試過C#正則表達式替換爲正則表達式
output = Regex.Replace(input, "[[:de:(.*)]]", "{{de|(.*)}}");
但它並不複製<文本>。 我沒有其他想法如何正確替換。 希望你能幫助我。
我有一個問題,我想在某些文本中用「{{de | < text>}}」替換每個「[[:de:< text>]]」。我試過C#正則表達式替換爲正則表達式
output = Regex.Replace(input, "[[:de:(.*)]]", "{{de|(.*)}}");
但它並不複製<文本>。 我沒有其他想法如何正確替換。 希望你能幫助我。
使用一個懶惰的圓點圖案和反向引用和逃避[
符號:
output = Regex.Replace(input, @"\[\[:de:(.*?)]]", "{{de|$1}}");
如果de:
和]]
之間的文本可以包含換行符,使用RegexOptions.Singleline
修改。
查看regex demo。
另請參閱[正則表達式中的替換](https://msdn.microsoft.com/en-us/library/ewy2t5e0(v = vs.110).aspx)以獲取有關.NET替換反向引用的更多詳細信息。 –
你錯過了模式前面的'@'。 – aloisdg
@aloisdg:當然,修正。 –
如果封裝內羣體的一切,你可以受益MatchEvaluator的。 Try it online。
public static void Main()
{
var input = "[[:de:Hello World]]";
var pattern = @"(\[\[:de:)(.+)(\]\])";
var output = Regex.Replace(input, pattern, m => "{{de|" + m.Groups[2].Value + "}}");
Console.WriteLine(output);
}
輸出
{{de|Hello World}}
可以爲更復雜的場景保存匹配評估程序,這裏的替換反向引用就足夠了。貪婪點也會混淆一行中包含多個匹配的輸出。 –
@WiktorStribiżew我同意。 – aloisdg
你真的需要正則表達式?我認爲你只能使用字符串替換方法;
output = input.Replace("[[:de:(.*)]]", "{{de|(.*)}}");
'(。*)'是一個正則表達式。 OP希望將'[[:de:Hello World]]'替換爲'{{de | Hello World}}'。 – aloisdg
使用String.Replace。如果你不想把''[[:de:(。*)]]''作爲正則表達式,就不要求它。 –