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

编程入门 行业动态 更新时间:2024-10-26 00:24:14
本文介绍了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 匹配相同数量的字符

本文发布于:2023-11-04 00:45:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1556493.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符   数量   Regex   Replace

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!