Los modificadores de la conducta de una expresión regular pueden ser
empotrados en una subexpresión usando el formato (?pimsx-imsx)
.
Véase el correspondiente texto Extended Patterns de la sección 'Extended-Patterns' en perlre:
One or more embedded pattern-match modifiers, to be turned on (or turned
off, if preceded by '-
' ) for the remainder of the pattern or the remainder
of the enclosing pattern group (if any). This is particularly useful
for dynamic patterns, such as those read in from a configuration file,
taken from an argument, or specified in a table somewhere. Consider
the case where some patterns want to be case sensitive and some do not:
The case insensitive ones merely need to include (?i) at the front of
the pattern. For example:
1. $pattern = "foobar"; 2. if ( /$pattern/i ) { } 3. 4. # more flexible: 5. 6. $pattern = "(?i)foobar"; 7. if ( /$pattern/ ) { }
These modifiers are restored at the end of the enclosing group. For example,
1. ( (?i) blah ) \s+ \1
will matchblah
in any case, some spaces, and an exact (including the case!) repetition of the previous word, assuming the/x
modifier, and no/i
modifier outside this group.
El siguiente ejemplo extiende el ejemplo visto en
la sección
3.1.1
eliminando los comentarios /* ... */
y // ...
de un programa C. En dicho ejemplo se usaba el modificador s
para hacer que el punto casara con cualquier carácter:
casiano@tonga:~/Lperltesting$ cat -n extendedcomments.pl 1 #!/usr/bin/perl -w 2 use strict; 3 4 my $progname = shift @ARGV or die "Usage:\n$0 prog.c\n"; 5 open(my $PROGRAM,"<$progname") || die "can't find $progname\n"; 6 my $program = ''; 7 { 8 local $/ = undef; 9 $program = <$PROGRAM>; 10 } 11 $program =~ s{(?xs) 12 /\* # Match the opening delimiter 13 .*? # Match a minimal number of characters 14 \*/ # Match the closing delimiter 15 | 16 (?-s)//.* # C++ // comments. No s modifier 17 }[]g; 18 19 print $program;Sigue un ejemplo de ejecución. Usaremos como entrada el programa C:
casiano@tonga:~/Lperltesting$ cat -n ehello.c 1 #include <stdio.h> 2 /* first 3 comment 4 */ 5 main() { // A C++ comment 6 printf("hello world!\n"); /* second comment */ 7 } // final commentAl ejecutar el programa eliminamos los comentarios:
casiano@tonga:~/Lperltesting$ extendedcomments.pl ehello.c | cat -n 1 #include <stdio.h> 2 3 main() { 4 printf("hello world!\n"); 5 }