简体   繁体   English

C# Regex.Replace 匹配相同数量的字符

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

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我想知道如何将未知数量的等号的正则表达式匹配,即不少于 2 ... 替换为相同数量的下划线

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编辑:最好是在所有语言中兼容的正则表达式解决方案

You can use Regex.Replace(String, MatchEvaluator) instead and analyze math:您可以改用Regex.Replace(String, MatchEvaluator)并分析数学:

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

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.如果一行中有超过 2 个= ,那么在每个= ,我们都会在前面或后面找到一个=

This only works if the language supports look-behind, which includes C#, Java, Python, PCRE... and excludes JavaScript.这仅在语言支持后视(包括 C#、Java、Python、PCRE... 并且不包括 JavaScript)时才有效。

However, since you can pass a function to String.replace function in JavaScript, you can write code similar to Alexei Levenkov's answer.但是,由于您可以在 JavaScript 中将函数传递给String.replace函数,因此您可以编写类似于 Alexei Levenkov 的答案的代码。 Actually, Alexei Levenkov's answer works in many languages (well, except Java).实际上,Alexei Levenkov 的答案适用于多种语言(当然,Java 除外)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM