“(?...) 的正则表达式解释“和”(2)”


regular expression explanations for `(?…)` and `(2)`

我需要一些帮助来理解一些正则表达式。我看到了这样的代码

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   

代码有什么问题吗?

(2)表示第二个匹配的片段,从这里开始:( '( )? 。所以整行是这样工作的:如果第二个片段匹配(意味着有左括号),那么我们需要确保有右括号。

2)表示条件#2,或者您可以说第二个捕获组,这意味着第二个()中的条件。这意味着如果有(那么必须有b )

在这里阅读

(?(1)then|else)

意味着如果到目前为止第一个捕获组参与了匹配尝试,则"then"部分必须匹配整个正则表达式才能匹配。如果第一个捕获组未参与匹配,则"else"部分必须匹配才能匹配整个正则表达式。

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

同样在 PHP 中

猜猜它说它做什么,寻找存储在第二个结果中的区号,如果是这样,它也应该关闭。这意味着这可能适用于某种"如果 result-2 有效 => 关闭,否则 => 什么都没有"。

正则表达式不是我最好的朋友,所以我希望我是对的......但我也很难以解释/创建它们,所以也许现在任何人都可以在这里教我一件事;-)

顺便说一句,如果你在谷歌上搜索"PHP 正则表达式备忘单",有一些结果可能会引起你的兴趣,至少它们对我来说很有趣。