[英]Perl regular expressions
我正在阅读一些涉及正则表达式的代码,遇到了一些麻烦。
有人可以解释一下,并举例说明它可以解析的文本吗?
if(/\|\s*STUFF(\d+)\s*\|\s*STUFF(\d+)/)
{
$a = $1;
$b = $2;
}
与之匹配的一个字符串是|STUFF1|STUFF2
。
(?-imsx:\|\s*STUFF(\d+)\s*\|\s*STUFF(\d+))
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):
----------------------------------------------------------------------
\| '|'
----------------------------------------------------------------------
\s* whitespace (\n, \r, \t, \f, and " ") (0 or
more times (matching the most amount
possible))
----------------------------------------------------------------------
STUFF 'STUFF'
----------------------------------------------------------------------
( group and capture to \1:
----------------------------------------------------------------------
\d+ digits (0-9) (1 or more times (matching
the most amount possible))
----------------------------------------------------------------------
) end of \1
----------------------------------------------------------------------
\s* whitespace (\n, \r, \t, \f, and " ") (0 or
more times (matching the most amount
possible))
----------------------------------------------------------------------
\| '|'
----------------------------------------------------------------------
\s* whitespace (\n, \r, \t, \f, and " ") (0 or
more times (matching the most amount
possible))
----------------------------------------------------------------------
STUFF 'STUFF'
----------------------------------------------------------------------
( group and capture to \2:
----------------------------------------------------------------------
\d+ digits (0-9) (1 or more times (matching
the most amount possible))
----------------------------------------------------------------------
) end of \2
----------------------------------------------------------------------
) end of grouping
----------------------------------------------------------------------
\|\s*STUFF(\d+)\s*\|\s*STUFF(\d+)
\\|
寻找文字管道字符|
。
\\s*
寻找任何数字(零个或多个)空白字符。
STUFF
查找字符串STUFF
(\\d+)
查找任意位数(一个或多个),并将其保存到$1
。
\\s*
查找任意数量的空格字符(零个或多个)
然后重复一次,并将下一个数字序列保存在$2
。
如果正则表达式匹配,我们知道必须定义$1
和$2
(即它们具有值)。
在这种情况下,我们将$1
分配给变量$a
,将$2
分配给$b
。
由于没有提供要匹配的显式字符串,因此将隐式使用$_
变量。
示例文字:
foo bar |STUFF123|STUFF456 baz bar foo
和
foo |
STUFF0
|STUFF1234567890bar
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.