in reply to match *bold* formatting, but avoid html

I have fuzzy memory about backreferences in character classes. I recall hearing that they work in quite new versions of Perl and then being straightened out that they don't work and likely never will. That is, that [^\1] always matches any character but "\1" (CTRL-A, "\cA"). You seem to think that [^\2] works and I'm not trying to say you are wrong. Just that you might be wrong.

So, instead of [^\2] you might want (?!\2) (which wouldn't be the same if $2 were more than a single character).

Also, <[^<>]+> is better, otherwise:

Well, if < _$20_, you *need* <a href="...">this</a>
won't expand either of the _ and * formatting. (Below I took the liberty of turning such unmatched <s into &lt; as well.)

In a situation like this, I'd "tokenize" rather than "match":

use warnings; use strict; sub reg_fix { my $text = shift(@_); # I guessed what you wanted =equals= to indicate: my %tag= qw( / em * b _ u = strike ); my %open; @open{ qw( / * _ = ) }= (); my @tokens= $text =~ m{ ( <[^<>]+> | [/*_=] | [^</*_=]+ | < ) }gmx; my @nested; for my $token ( @tokens ) { if( "<" eq $token ) { $token= "&lt;"; } elsif( exists $open{$token} ) { if( ! defined $open{$token} ) { $open{$token}= \$token; push @nested, $token; } else { ${$open{$token}}= "<$tag{$token}>"; my $nest; do { $nest= pop @nested; undef $open{$nest}; } while( $nest ne $token ); $token= "</$tag{$token}>"; } } } return join '', @tokens; } print reg_fix($_) for <DATA>; __END__ go/to <img src='http://allpoetry.com:8080/images/smile/happy.gif'> /th +x/ <img src='http://allpoetry.com:8080/images/smile/happy.gif'> _sill +y *to_* Well, if < _$20_, you *need* <a href="...">this</a>
which produces:
go<em>to <img src='http://allpoetry.com:8080/images/smile/happy.gif'> +</em>thx/ <img src='http://allpoetry.com:8080/images/smile/happy.gif' +> <u>silly *to</u>* Well, if &lt; <u>$20</u>, you <b>need</b> <a href="...">this</a>

Note how I prevent mis-nesting of attributes.

                - tye