Markus Rost
Markus Rost

Reputation: 11

C# Regex replace with Regex

I have a problem, I want to replace every "[[:de:<text>]]" with "{{de|<text>}}" in some text. I tried with

output = Regex.Replace(input, "[[:de:(.*)]]", "{{de|(.*)}}");

but it doesnt copy the <text>. I have no other idea how to replace this correctly. Hope you can help me.

Upvotes: 1

Views: 312

Answers (3)

Orhun Karapinar
Orhun Karapinar

Reputation: 45

Do you really need regex ? I think you can only use string replace method;

output = input.Replace("[[:de:(.*)]]", "{{de|(.*)}}");

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627469

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.

See the regex demo.

enter image description here

Upvotes: 2

aloisdg
aloisdg

Reputation: 23541

If you encapsulate everything inside groups, you can benefit of a 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}}

Upvotes: 0

Related Questions