Retrieve groups from a regular expression in Perl

7

I'm running this regular expression to separate the digits of a version:

([\d]+)+

As you can see in this example , it works well enough to cover my needs.

However, I have to add this to a Perl script, which is not my specialty. I run my regex and then try to retrieve the values from the group.

$version="2.2.1-ALPHA30";
$version=~/([\d]+)+/g;
print "major:$1 minor:$2 revision:$3 build:$4\n"

First that I only have $1 that is shown, the others are empty.

And finally, I see no way of knowing how many values were found by regex.

    
asked by anonymous 03.05.2015 / 17:54

3 answers

4

The expression ([\d]+)+ does not require the bracket, nor the second addition operator. If you need to put the results in array to count the number of occurrences found, do:

$version="2.2.1-ALPHA30";
my @numeros = $version =~ /(\d+)/g;
$quantidade = scalar(@numeros);

print "Foram encontrados $quantidade números!\n";
print join(", ", @numeros);

DEMO

If you need to know the number of occurrences and need to work individually with each, assign each variable a catch:

$version="2.2.1-ALPHA30";;
my $quantidade = () = my ($major, $minor, $revision, $build) = $version =~ /(\d+)/g;

print "Foi encontrado $quantidade resultados!\n";
print "$major, $minor, $revision, $build\n";

DEMO

    
03.05.2015 / 18:11
3

Previous answers already say everything ... One thing I like about Perl is that regular expressions marry well with control structures: captures and control structures

Capture groups produce lists when used in list context (as before)

@r = $version =~ m/(\d+)/g;

and return True / False in Boolean context. These implicit conversions
can be used in various untested structures:
(1) if

$p = "stardict_3.0.4-1"
if($p =~ m/(.*?)_(\d+[.\d-]*)/ ) {  
    print "base=$1   version=$2 }

(2) for

$t="era uma vez um gato maltez";
for($t =~ m/(\w+)/g) { 
    $ocorrencia{$_}++ }

(3) while

$ls='ls';
while($ls =~ m/(\S+?)\.(\w+)/g ){ 
   print "nome=$1; extensao:$2\n"}

(4) s/expressãoregular/ perl /e

$text= "volto amanha";
$text =~ s/amanha/ 'date --date="tomorrow"' /ge
    
05.05.2015 / 16:52
1

Try this:

$version="2.2.1-ALPHA30";
my @resultados = $version=~/([\d]+)+/g;
print join(", ", @resultados);

I used print only to show all the results that were captured. You can use the array to access each of the results.

If you just want the number you can use the array as a scale.

    
03.05.2015 / 18:10