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:
won't expand either of the _ and * formatting. (Below I took the liberty of turning such unmatched <s into < as well.)Well, if < _$20_, you *need* <a href="...">this</a>
In a situation like this, I'd "tokenize" rather than "match":
which produces: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= "<"; } 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>
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 < <u>$20</u>, you <b>need</b> <a href="...">this</a>
Note how I prevent mis-nesting of attributes.
- tyeIn reply to Re: match *bold* formatting, but avoid html (tokenize)
by tye
in thread match *bold* formatting, but avoid html
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |