Menocode
Menocode

Reputation: 43

Perl regex capturing multiple instances

$string = "BLAH1234 xyz BALH3214 xxyyzz BALH3452"

I want to capture all instances of 4 capital letters in a row followed by 4 numbers.

I did: $line =~ /([A-Z]{4}[0-9]{4})/g but I can only capture the first instance. When I do $2 it says it's uninitialized.

How can I capture all instances?

Upvotes: 1

Views: 60

Answers (2)

hwnd
hwnd

Reputation: 70750

my @matches = $string =~ /[A-Z]{4}\d{4}/g;

Upvotes: 1

dawg
dawg

Reputation: 104102

Given:

$ echo "$tgt"
"BLAH1234 xyz BALH3214 xxyyzz BALH3452"

You can do:

$ echo "$tgt" | perl -lne 'print join("|", /[A-Z]{4}\d{4}/g)'
BLAH1234|BALH3214|BALH3452

Or, more explicitly:

my $line="BLAH1234 xyz BALH3214 xxyyzz BALH3452";
for ($line=~/[A-Z]{4}\d{4}/g) {
    print "$_\n";
}

A global find returns a list.

Upvotes: 0

Related Questions