regexperlmarkdownitalic

Substitute the markdown italic to html using regex in Perl


To convert the markdown italic text $script into html, I've written this:

my $script = "*so what*";
my $res =~ s/\*(.)\*/$1/g;
print "<em>$1</em>\n";

The expected result is:

<em>so what</em>

but it gives:

<em></em>

How to make it give the expected result?


Solution

  • Problems:

    Fix:

    $script =~ s{\*([^*]+)\*}{<em>$1</em>}g;
    print "$script\n";
    

    or

    my $res = $script =~ s{\*([^*]+)\*}{<em>$1</em>}gr;
    print "$res\n";
    

    But that's not it. Even with all the aforementioned problems fixed, your parser still has numerous other bugs. For example, it misapplies italics for all of the following: