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

后端 未结 2 605
太阳男子
太阳男子 2021-01-22 10:01

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:



        
相关标签:
2条回答
  • 2021-01-22 10:11

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

    string result = new Regex("(={2,})")
        .Replace(text, match => new string('_', match.ToString().Length)); 
    
    0 讨论(0)
  • 2021-01-22 10:30

    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).

    0 讨论(0)
提交回复
热议问题