1

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.

1
  • Use String.Replace. If you don't want it to treat "[[:de:(.*)]]" as a regex, don't ask it to. Commented Apr 14, 2017 at 15:06

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

Also, see Substitutions in Regular Expressions for more details on .NET replacement backreferences.
You miss the @ before the pattern.
@aloisdg: Sure, fixed.
0

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}}

2 Comments

Match evaluator can be saved for more complex scenarios, replacement backreferences are enough here. The greedy dot will also mess the output that contains several matches on a single line.
@WiktorStribiżew I agree.
0

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

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

1 Comment

(.*) is a regex. OP wants to replace [[:de:Hello World]] to {{de|Hello World}}.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.