Regex- replace sequence of one character with same number of another character

丶灬走出姿态 提交于 2020-01-10 03:37:12

问题


Let's say I have a string like this:

=====

and I want to replace it with this:

-----

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:

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

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

I know I can do this:

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

or this:

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

Is this possible?


回答1:


It's possible with Perl:

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

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 ===="



回答2:


Depending what language you're using. Basically, in some languages, you can put code in the right side of the regexp, allowing you to do something like this: (this is in perl):

s/(=+)/(length($1) > 3 ? "-" : "=") x length($1)/e

The 'e' flag tells perl to execute the code in the right side of the expression instead of just parsing it as a string.



来源:https://stackoverflow.com/questions/7337995/regex-replace-sequence-of-one-character-with-same-number-of-another-character

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!