in reply to Output minimal occurrences of matching regex(es)
You can declare the variable before the condition and only populate it depending on it:
or you can use the conditional operator (the "ternary"), shown below.my @regexes; if ($param eq 'mod') { @regexes = ... } else { @regexes = ... }
To match the entities involved in ;\s&, you need to extend the regex:
i.e. an ampersand, not semicolon at least once, semicolon, space, and an entity again.&[^;]+;\s&[^;]+;
Here's a complete example. Running it with script.pl 1.xml searches for the original regexes, specifyin any true parameter (e.g. script.pl 1.xml 1) after the file uses the modified regexes. I also added the grouping parentheses to the matching and $1 to the output to show which part of the string actually matched the regex.
Update: Fixed formatting, thanks Discipulus.#!/usr/bin/perl use warnings; use strict; my ($infile, $param) = @ARGV; my @regexes = $param ? (qr/&[^;]+;\s&[^;]+;/) : (qr/–§/, qr/–Ü/, qr/ß§/); open my $in, '<', $infile or die "Cannot open $infile for reading: $!" +; my $xml; { local $/; $xml = <$in>; } open my $out, '>', 'pairs.txt' or die $!; print {$out} "Find pair of entities without/with separating space\n\ni +nput file: "; print {$out} "$infile"; print {$out} "\n====================================================== +==================\n\n"; for my $i (0 .. $#regexes) { my $regex = $regexes[$i]; $regex =~ s/^\(\?\^://; $regex =~ s/\)$//; print {$out} "$regex: $1\n" while $xml =~ /($regex)/g; } close $in; close $out;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Output minimal occurrences of matching regex(es)
by LexPl (Beadle) on Nov 14, 2024 at 11:16 UTC | |
by hippo (Archbishop) on Nov 14, 2024 at 11:49 UTC |