我正在阅读一些涉及正则表达式的代码并且遇到了一些麻烦。
有人可以解释一下并举例说明它会解析的文本吗?
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