[英]Perl regular expression and arguments
The following Perl example is part of long Perl script. 以下Perl示例是长Perl脚本的一部分。
This script takes the results from ifconfig -a
and prints the IP address. 该脚本从
ifconfig -a
获取结果并打印IP地址。
Can someone explain how $1
gets the IP address? 有人可以解释
$1
如何获得IP地址吗?
And what the regular expression 以及正则表达式是什么
$RESULTS =~ /addr:(\S+)\s+/
means? 手段?
my $COMMAND = "ifconfig -a | grep inet | grep -v 127.0.0.1 | head -1";
my $RESULTS = `$COMMAND`;
chomp $RESULTS;
# inet addr:106.13.4.9 Bcast:106.13.4.255 Mask:255.255.255.0
# inet 106.13.4.9 netmask ffffff80 broadcast 106.13.4.127
if ( $RESULTS =~ /addr:(\S+)\s+/ ) {
$IpAddress = $1;
}
elsif ( $RESULTS =~ /inet\s+(\S+)\s+/ ) {
$IpAddress = $1;
}
print "IpAddress = $IpAddress\n";
If a =~
match expression is true, the special variables $1
, $2
, ... will be the substrings that matched parts of the pattern in parenthesis. 如果
=~
〜match表达式为true,则特殊变量$1
, $2
,...将是与括号中的模式部分匹配的子字符串。 $1
matches the first left parenthesis, $2
the second left parenthesis, and so on. $1
匹配第一个左括号, $2
匹配第二个左括号,依此类推。
\\S
matches any non-whitespace character, \\S
匹配任何非空白字符,
+
match 1 or more times, +
匹配1次或多次,
\\s
matches any whitespace character (space, tab, newline), \\s
匹配任何空格字符(空格,制表符,换行符),
So in your regex it matches addr:(any non-whitespace character 1 or more time)matches any whitespace character one or more time
. 因此,在您的正则表达式中,它与
addr:(any non-whitespace character 1 or more time)matches any whitespace character one or more time
。 And $1
in capturing the value in parenthesis. 和
$1
表示括号中的值。
See this question to understand $1
: What does $1 mean in Perl? 请参阅以下问题以了解
$1
: Perl中$ 1意味着什么?
=~
is the matches operator in perl and evaluates to true if a string (here $RESULTS
) can be matched with a regular expression (here /addr:(\\S+)\\s+/
) =~
是perl中的matchs运算符,如果字符串(此处$RESULTS
)可以与正则表达式(此处为/addr:(\\S+)\\s+/
)匹配,则计算结果为true /addr:(\\S+)\\s+/
When a regular expression is matched in perl, variables are automatically assigned: 在perl中匹配正则表达式时,将自动分配变量:
$&
holds the part matched by the whole expression $&
保留与整个表达式匹配的部分 $1
holds the part matched by the first capture group (set of parantheses) $1
持有与第一个捕获组(括号组)匹配的部分 $2
the part by the second capture group $2
$1
, $2
, $&
etc will capture the value the last successful match. $1
, $2
, $&
等将捕获最后一次成功匹配的值。
\\S+
matches any and negates \\s
(whitespace). \\S+
匹配任何值并取反\\s
(空格)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.