Regex- replace sequence of one character with same

2019-01-26 06:07发布

问题:

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.



标签: regex replace