Cheok Yan Cheng
Cheok Yan Cheng

Reputation: 42690

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?

Upvotes: 1

Views: 252

Answers (3)

hillu
hillu

Reputation: 9611

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'.

Upvotes: 1

Zaid
Zaid

Reputation: 37146

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};
    }
}

Upvotes: 0

Svante
Svante

Reputation: 51501

Add the g modifier and put it into a while loop:

while ($line =~ /GUIBundle\.getString\("([^"]+)"\)/g) { ...

Upvotes: 4

Related Questions