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?
To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).
How to use RegEx with . replace in JavaScript. To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring.
For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.
\\. matches the literal character . . the first backslash is interpreted as an escape character by the Emacs string reader, which combined with the second backslash, inserts a literal backslash character into the string being read. the regular expression engine receives the string \.
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 ===="
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With