[英]C# Regex replace with Regex
I have a problem, I want to replace every "[[:de:<text>]]" with "{{de|<text>}}" in some text. 我有一个问题,我想用某些文本中的“ {{de | <text>}}}”替换每个“ [[::: <text>]]””。 I tried with 我尝试过
output = Regex.Replace(input, "[[:de:(.*)]]", "{{de|(.*)}}");
but it doesnt copy the <text>. 但它不会复制<text>。 I have no other idea how to replace this correctly. 我没有其他想法如何正确地替换它。 Hope you can help me. 希望您能够帮助我。
Use a lazy dot pattern and backreferences and escape the [
symbols: 使用惰性点模式和反向引用并转义[
符号:
output = Regex.Replace(input, @"\[\[:de:(.*?)]]", "{{de|$1}}");
If the text between de:
and ]]
can contain line breaks, use RegexOptions.Singleline
modifier. 如果de:
和]]
之间的文本可以包含换行符,请使用RegexOptions.Singleline
修饰符。
See the regex demo . 参见regex演示 。
If you encapsulate everything inside groups, you can benefit of a MatchEvaluator. 如果将所有内容封装在组中,则可以使用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);
}
output 产量
{{de|Hello World}}
Do you really need regex ? 您真的需要正则表达式吗? I think you can only use string replace method; 我认为您只能使用字符串替换方法;
output = input.Replace("[[:de:(.*)]]", "{{de|(.*)}}");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.