C# Regex.Replace 匹配相同数量的字符 [英] C# Regex.Replace match by the same amount of characters

查看:72
本文介绍了C# Regex.Replace 匹配相同数量的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何将未知数量的等号(不少于 2...)的正则表达式匹配替换为相同数量的下划线

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 ?

最好是兼容所有语言的正则表达式解决方案

Prefferably a regex solution thats compatible in all languages

推荐答案

一个不太明确的答案(在代码清晰度方面):

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

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

如果连续有超过 2 个 =,那么在每个 = 处,我们都会在前面或后面找到一个 =.

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

这仅在语言支持后视(包括 C#、Java、Python、PCRE...但不包括 JavaScript)时有效.

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

但是,由于您可以在 JavaScript 中将函数传递给 String.replace 函数,因此您可以编写类似于 Alexei Levenkov 的答案的代码.实际上,Alexei Levenkov 的答案适用于多种语言(当然,Java 除外).

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

这篇关于C# Regex.Replace 匹配相同数量的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆