简体   繁体   中英

Perl Regular Expression - Dynamic Matches

Let's say I want to match and capture 5 integers separated by one or more spaces - example input:

1111 234 3333 456 7890

I could do this:

my $input = '1111        234            3333          456    7890';
if($input =~ /^\s*([0-9]+)\s+([0-9]+)\s+([0-9]+)\s+([0-9]+)\s+([0-9]+)/)
{
  #$1 = '1111', $2 = '234', $3 = '3333', $4= '456', $5 = '7890'
}

But I want to do something like this to keep the regex simpler, rather than repeating each int 5 times explicitly:

my $input = '1111        234            3333          456    7890';
if($input =~ /^((\s*[0-9]+){5})/)
{
  #$1 = '1111        234            3333          456    7890';
  #$2 = ' 7890'
  #all other capture variables are undefined
}

However, the captures don't seem to work out.

Is there a way I can I do this and still access my 5 captures?

Even better would be an unknown number of captures:

my $input = '1111        234            3333          456    7890';
if($input =~ /^((\s*[0-9]+)+)/)
{
   #foreach capture 1..N do something...
}
my @numbers = $input =~ /\d+/g;

全局标志将返回列表上下文中的所有匹配项,这些匹配项将存储在您的数组中。

If you know what your delimiter is (in this case, one or more spaces), then you don't need a regex to capture what you want. You can use split .

use strict;
use warnings;

my $input = "1111        234            3333          456    7890";
my @ints=split /\s+/,$input;
print "$_\n" foreach(@ints);

Which produces the output:

1111
234
3333
456
7890

Is the pattern of the line always digit groups separated by spaces? If so, rather than the regex, why not split into array based on whitespace

@outArray = split (/ +/,$input);

The following would capture the first 5 integers and ignore any after that if thats what you're after. I may not be entirely clear.

#!/usr/bin/perl
use strict;
use warnings;

my $in = '1111        234            3333          456    7890 12 13';

my @ints = (split ' ', $in)[0 .. 4];

print "@ints\n";

Prints:

1111 234 3333 456 7890

Chris

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM