我正在编辑Perl文件,但我不理解这个正则表达式比较.有人可以向我解释一下吗?
if ($lines =~ m/(.*?):(.*?)$/g) { } ..
Run Code Online (Sandbox Code Playgroud)
这里发生了什么?$lines是文本文件中的一行.
Can*_*ice 12
将其分解为多个部分:
$lines =~ m/ (.*?) # Match any character (except newlines)
# zero or more times, not greedily, and
# stick the results in $1.
: # Match a colon.
(.*?) # Match any character (except newlines)
# zero or more times, not greedily, and
# stick the results in $2.
$ # Match the end of the line.
/gx;
Run Code Online (Sandbox Code Playgroud)
因此,这将匹配字符串":"(它匹配零个字符,然后是冒号,然后是行结尾前的零个字符,$1并且$2是空字符串),或者"abc:"($1 = "abc",$2是一个空字符串),或"abc:def:ghi"($1 = "abc"和$2 = "def:ghi").
如果你传入一个不匹配的行(看起来这将是字符串不包含冒号),那么它将不会处理括号内的代码.但如果它匹配,则括号内的代码可以使用和处理特殊$1和$2变量(至少,直到下一个正则表达式出现,如果括号内有一个).
有一个工具可以帮助理解正则表达式:YAPE :: Regex :: Explain.
忽略g修改器,这里不需要:
use strict;
use warnings;
use YAPE::Regex::Explain;
my $re = qr/(.*?):(.*?)$/;
print YAPE::Regex::Explain->new($re)->explain();
__END__
The regular expression:
(?-imsx:(.*?):(.*?)$)
matches as follows:
NODE EXPLANATION
----------------------------------------------------------------------
(?-imsx: group, but do not capture (case-sensitive)
(with ^ and $ matching normally) (with . not
matching \n) (matching whitespace and #
normally):
----------------------------------------------------------------------
( group and capture to \1:
----------------------------------------------------------------------
.*? any character except \n (0 or more times
(matching the least amount possible))
----------------------------------------------------------------------
) end of \1
----------------------------------------------------------------------
: ':'
----------------------------------------------------------------------
( group and capture to \2:
----------------------------------------------------------------------
.*? any character except \n (0 or more times
(matching the least amount possible))
----------------------------------------------------------------------
) end of \2
----------------------------------------------------------------------
$ before an optional \n, and the end of the
string
----------------------------------------------------------------------
) end of grouping
----------------------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15982 次 |
| 最近记录: |