use warnings; use strict; my $anchors = qr{ (?(DEFINE) (? (?> [^\[\]]+ | \[ (?&nested_brackets) \] )* ) ) \[ (? (?&nested_brackets) ) \] \( (? [ \t]* ? [ \t]* (?: (?['"]) .*? \k )? ) \) }xs; my $input = <<'END'; blah blah [click me](click me) more stuff blah [link here](link here) blah blah END my $expect = <<'END'; blah blah [click me](/click-me) more stuff blah [link here](/link-here) blah blah END (my $output = $input) =~ s{$anchors}{ my ($t, $l) = @+{qw/ text link /}; $l =~ s/\s+/-/g; "[$t](/$l)" }ge; use Test::More tests=>1; is $output, $expect;