[英]Perl assign regex match groups to variables
我有一個以下格式的字符串: _num1_num2
。 我需要為某些變量分配num1
和num2
值。 我的正則表達式是(\\d+)
,它在Rubular.com上顯示了正確的匹配組,但我不知道如何將這些匹配組分配給某些變量。 有誰能夠幫助我? 謝謝你。
使用g-modifier還可以取消分組括號:
my ($five, $sixty) = '_5_60' =~ /\d+/g;
這允許任何整數分離,但它不驗證輸入格式。
在第一個答案中使用全局標志有點令人困惑。 正則表達式/ _(\\ d +)_(\\ d +)/已經捕獲了兩個整數。 此外,g修飾符嘗試多次匹配。 所以這是多余的。
恕我直言,當匹配數未知或簡化正則表達式時,應使用g修飾符。
據我所知,這與JavaScript中的工作方式完全相同。
這里有些例子:
use strict;
use warnings;
use Data::Dumper;
my $str_a = '_1_22'; # three integers seperated by an underscore
# expect two integert
# using the g modifier for global matching
my ($int1_g, $int2_g) = $str_a =~ m/_(\d+)/g;
print "global:\n", Dumper( $str_a, $int1_g, $int2_g ), "\n";
# match two ints explicitly
my ( $int1_e, $int2_e) = $str_a =~ m/_(\d+)_(\d+)/;
print "explicit:\n", Dumper( $str_a, $int1_e, $int2_e ), "\n";
# matching an unknown number of integers
my $str_b = '_1_22_333_4444';
my @ints = $str_b =~ m/_(\d+)/g;
print "multiple integers:\n", Dumper( $str_b, \@ints ), "\n";
# alternatively you can use split
my ( $int1_s, $int2_s ) = split m/_/, $str_a;
print "split:\n", Dumper( $str_a, $int1_g, $int2_g ), "\n";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.