开发者

How do I grab only one capture out of a Perl regular expression?

开发者 https://www.devze.com 2022-12-12 18:23 出处:网络
Is there an easier way to grab only one element out of a match other than doing the followng: my $date = ($xml_file =~ m/(\\d+)-sys_char/)[0];

Is there an easier way to grab only one element out of a match other than doing the followng:

my $date = ($xml_file =~ m/(\d+)-sys_char/)[0];
# or
my $date = $1 if $xml_file =~ /(\d+)-sys_char/;

Is there a flag to specify that m doesn't return an array but just one concaten开发者_运维技巧ated value of all the $# matches, so I can do:?

my $date = ($xml_file =~ mSOMEOPT/(\d+)-sys_char/);

removing the 0 from the end?


You want:

my ($date) = ($xml_file =~ m/(\d+)-sys_char/);

This will get you $1 in $date. As for the second part of your question, there's no way to get all of the numbered matches in a single variable, but you can get them all into an array like this:

my @matches = ($xml_file =~ m/(\d+)-sys_char/);

These are actually the same syntax: when the left hand side of a match like this is an array, then an array containing all of the submatches is returned. The first version make ($date) into a one-element array, throwing away the rest of the sub-matches.


my ($date) = $xml_file =~ m/(\d+)-sys_char/;

if ( defined $date ) {

}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号