2011-05-09 122 views
0

我需要一些帮助来理解一点正则表达式。我见过这样正则表达式帮助

preg_match("/^ 

      (1[-\s.])? # optional '1-', '1.' or '1' 
      (\()?  # optional opening parenthesis 
      \d{3}  # the area code 
      (?(2) \)) # if there was opening parenthesis, close it 
      [-\s.]?  # followed by '-' or '.' or space 
      \d{3}  # first 3 digits 
      [-\s.]?  # followed by '-' or '.' or space 
      \d{4}  # last 4 digits 

      $/x",$number) 

我都明白,但不明白如何(?(2) \))真正的工作......西隧呢代码?和(2)代表。

问题更新...

我读你的答案..当我改变像

preg_match("/^ 

      (1[-\s.])? # optional '1-', '1.' or '1' 
      \d{3}  # the area code 
      (\()?  # optional opening parenthesis 
      (?(3) \)) # if there was opening parenthesis, close it 
      [-\s.]?  # followed by '-' or '.' or space 
      \d{3}  # first 3 digits 
      [-\s.]?  # followed by '-' or '.' or space 
      \d{4}  # last 4 digits 

      $/x",$number) 

我得到错误,如

Compilation failed: reference to non-existent subpattern 

代码是有anythign毛病码?

回答

2

(2)指条件#2也可以说第二捕获组,这意味着在第二()。它条件意味着如果有(那么必定b )

Read here

(?(1)then|else) 

含义如果第一个捕获组到目前为止参加了匹配尝试,那么“then”部分必须匹配整个正则表达式才能匹配。如果第一个捕获组没有参加比赛,那么“else”部分必须匹配整个正则表达式才能匹配。

eg: (a)?(?(1)b|c) matches ab, the first c and the second c in babxcac 

Also in PHP

+0

看到我的问题更新.. – Hacker 2011-05-09 05:13:59

+0

@pradeep更好地应用'前瞻'和'看后面'**声明** – diEcho 2011-05-09 05:20:43

+0

@pradeep我更新我的答案与PHP ..的链接,这将确保有助于你理解你正在谈论的概念 – diEcho 2011-05-09 05:25:14

3

(2)装置第二匹配的片段,从这里:(\()?。因此整条线的工作方式如下:如果第二个片段匹配(意味着有左括号),那么我们需要确保有右括号。

+0

看到我的问题更新 – Hacker 2011-05-09 05:14:23

1

猜猜它说的是什么,寻找存储在第二个结果中的区号,如果是,它也应该关闭。这意味着这可能适用于某种'if result-2 is valid => close,else => nothing'。

正则表达式是不是我最好的朋友,所以我希望我是对的。但我也有苦衷解释/创建它们,因此,也许任何人都可以在这里教我的事现在;-)

由方式,如果你谷歌的'PHP正则表达式备忘单',有安静的一些结果,可能是你的兴趣,至少他们对我很有趣。

+0

看到我的问题更新 – Hacker 2011-05-09 05:14:15