LanX has asked for the wisdom of the Perl Monks concerning the following question:
I need to transform or disable different (non-recursive!) markup-syntax-elements, in this case org-mode to kwiki.
Now links which are freely included in text are tricky...
for instance http://www.gmx.de or CamelCaseLink are valid links for kwiki ...
... and [[http://gmx.de][BlubBlub]] is a named link in org-mode.
As you can see are named-links allowed to include matches for http:://links or CamelCase words which mustn't be processed again. And links can occasionally include CamelCase words.
One approach is to OR the regexes with priority to the more complex ones, such that their matches are only processed once:
s/ ($named|$http|$camel) / tranform() /gxe
Now in the substitution part it's tricky to know which regex matched, thats why I use named captures.
The following code demonstrates what I'm doing!
(please note that for simplicity of the example my only transformation is to return the name of the match.)
I have the impression to reinvent the wheel and fiddling with %- doesn't seem stable...
So please show me easier approaches... :)
use warnings; use strict; #= ordered hash my @patterns=( named => '\[ \[ (?<link>.*?) \] \[ (?<name>.*?) \] \]', http => 'https?://[a-zA-Z./]+', camel => '[A-Z][a-z]+[A-Z][a-z]+', blank => '\s+', unknown => '.+?', ); my %patterns=@patterns; #= build regex pattern my @regexes; my @names; while ( my ($name,$regex) = splice @patterns,0,2) { push @names, $name; push @regexes,"(?<$name>$regex)"; } my $regex = '(' . join ("\n|", map {"\n\t$_"} @regexes) . "\n)"; print "Pattern:\n$regex\n\n"; # = return which pattern matched sub transform { my @matching= grep { $-{$_}[0] } @names ; return "@matching\t=>\t $1\n"; } #= apply regex while (<DATA>){ chomp; print "Line:\n$_\n\n"; s/$regex/transform()/gex; print "Result:\n$_\n\n"; } __DATA__ http://www.gmx.de CamelCase/WikiLink [[http://gmx.de][BlubBlub]]
OUTPUT:
Pattern: ( (?<named>\[ \[ (?<link>.*?) \] \[ (?<name>.*?) \] \]) | (?<http>https?://[a-zA-Z./]+) | (?<camel>[A-Z][a-z]+[A-Z][a-z]+) | (?<blank>\s+) | (?<unknown>.+?) ) Line: http://www.gmx.de CamelCase/WikiLink [[http://gmx.de][BlubBlub]] Result: http => http://www.gmx.de blank => camel => CamelCase unknown => / camel => WikiLink blank => named => [[http://gmx.de][BlubBlub]]
Cheers Rolf
( addicted to the Perl Programming Language)
|
---|