How to match 2 patterns within a single line
I have the following开发者_开发问答 Java code
fun(GUIBundle.getString("Key1"), GUIBundle.getString("Key2"));
I use Perl to parse the source code, to see whether "Key1" and "Key2" is found within $gui_bundle.
while (my $line = <FILE>) {
$line_number++;
if ($line =~ /^#/) {
next;
}
chomp $line;
if ($line =~ /GUIBundle\.getString\("([^"]+)"\)/) {
my $key = $1;
if (not $gui_bundle{$key}) {
print "WARNING : key '$key' not found ($name $line_number)\n";
}
}
}
However, for the way I write the code, I can only verify "Key1". How I can verify "Key2" as well?
Add the g
modifier and put it into a while
loop:
while ($line =~ /GUIBundle\.getString\("([^"]+)"\)/g) { ...
Just use the /g
modifier to the regular expression match, in list context:
@matches = $line =~ /GUIBundle\.getString\("([^"]+)"\)/g;
Given your example line, @matches
will contain strings: 'Key1'
and 'Key2'
.
Exchange the if
construct with a while
, and using the global-matching modifier, /g
:
while (my $line = <FILE>) {
$line_number++;
next if $line =~ /^#/;
chomp $line;
while ($line =~ /GUIBundle\.getString\("([^"]+)"\)/g) { #"
my $key = $1;
warn "key '$key' not found ($name $line_number)" unless $gui_bundle{$key};
}
}
精彩评论