正则表达式 - 用相同数量的另一个字符替换一个字符的序列 [英] Regex- replace sequence of one character with same number of another character

查看:21
本文介绍了正则表达式 - 用相同数量的另一个字符替换一个字符的序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个这样的字符串:

Let's say I have a string like this:

=====

我想用这个替换它:

-----

如果该字符的数量超过一定数量(我们会说 > 3),我只想替换它.

I only want to replace it if it has more than a certain number of that character (we'll say > 3).

所以,这些应该是替代品:

So, these should be the replacements:

=== -> ===
==== -> ----
===== -> -----

应用是我想用二级标记替换markdown中的所有一级标题标记,而不改变嵌入的代码块.

The application is I want to replace all level 1 heading marks in markdown with a level 2 mark, without changing embedded code blocks.

我知道我可以做到:

/=/-/g,但这会匹配任何带有等号 (if (x == y)) 的内容,这是不可取的.

/=/-/g, but this matches anything with an equals sign (if (x == y)), which is undesirable.

或者这个:

/====+/----/g,但这并没有考虑原始匹配字符串的长度.

/===+/----/g, but this doesn't account for the length of the original matched string.

这可能吗?

推荐答案

Perl 是可能的:

my $string = "===== Hello World ====";
$string =~ s/(====+)/"-" x length($1)/eg;
# $string contains ----- Hello World ----

标志/e 使 Perl 在 s///的第二部分执行表达式.你可以用 oneliner 试试这个:

Flag /e makes Perl execute expression in second part of s///. You may try this with oneliner:

perl -e '$ARGV[0] =~ s/(====+)/"-" x length($1)/eg; print $ARGV[0]' "===== Hello World ===="

这篇关于正则表达式 - 用相同数量的另一个字符替换一个字符的序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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