C# Regex.Replace match by the same amount of chara

2019-03-01 16:38发布

问题:

I like to know how to replace a regex-match of unknown amount of equal-signs, thats not less than 2... to the same amount of underscores

So far I got this:

text = Regex.Replace(text, "(={2,})", ""); 

What should I use as the 3rd parameter ?

EDIT: Prefferably a regex solution thats compatible in all languages

回答1:

A much less clear answer (in term of code clarity):

text = Regex.Replace(text, "=(?==)|(?<==)=", "_");

If there are more than 2 = in a row, then at every =, we will find a = ahead or behind.

This only works if the language supports look-behind, which includes C#, Java, Python, PCRE... and excludes JavaScript.

However, since you can pass a function to String.replace function in JavaScript, you can write code similar to Alexei Levenkov's answer. Actually, Alexei Levenkov's answer works in many languages (well, except Java).



回答2:

You can use Regex.Replace(String, MatchEvaluator) instead and analyze math:

string result = new Regex("(={2,})")
    .Replace(text, match => new string('_', match.ToString().Length));