2012-09-21 51 views
-1

我正在阅读一些涉及正则表达式并遇到麻烦的代码。Perl正则表达式

有人可以请解释它,并给出它将解析的文本的一个例子吗?

if(/\|\s*STUFF(\d+)\s*\|\s*STUFF(\d+)/) 
{ 
     $a = $1; 
     $b = $2; 
} 

回答

2

它匹配的一个字符串是|STUFF1|STUFF2

YAPE::Regex::Explain

(?-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 
---------------------------------------------------------------------- 
2
\|\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