简体   繁体   English

正则表达式-如何控制括号是标记子组还是进行其他操作(PHP-preg_match)

[英]Regular expressions - How to control whether parenthesis mark a sub group or do something else (PHP - preg_match)

How do I control whether parenthesis in my regular expression mark a sub group, do something else, or both? 如何控制正则表达式中的圆括号是否标记一个子组,是否做其他事情或两者都做?

For example if I have strings such as "AA12345" and "AB12345" and I want to preg_match for the first two letters which are always either AA or AB, I have: 例如,如果我有诸如“ AA12345”和“ AB12345”之类的字符串,并且我想对前两个始终为AA或AB的字母进行preg_match设置,则我可以:

preg_match('/(A(A|B)).*/',$string,$matches);

(I put the .* for the sake of this question because the rest of the string isn't relevant) (我为这个问题放了。*,因为字符串的其余部分无关紧要)

With this setup, assuming $string="AA12345", I'm getting $matches = 通过这种设置,假设$ string =“ AA12345”,我得到的是$ matches =

Array
(
[0] => AA12345
[1] => AA
[2] => A
)

I don't need or want the "[2] => A" as a result, but I can't remove the parenthesis from the regex because they are needed for the OR operator. 结果我不需要或想要“ [2] => A”,但是我不能从正则表达式中删除括号,因为OR运算符需要它们。 How do I deal with this? 我该如何处理? Just ignore the result, or is there a better way? 只是忽略结果,还是有更好的方法?

You can use a "non-capturing group" of the form (?:...) : 您可以使用(?:...)形式的“非捕获组”:

preg_match('/(A(?:A|B)).*/',$string,$matches);

As the documentation puts it: 正如文档所述

If an opening parenthesis is followed by "?:", the subpattern does not do any capturing, and is not counted when computing the number of any subsequent capturing subpatterns. 如果左括号后面跟有“?:”,则该子图案不执行任何捕获,并且在计算任何后续捕获子图案的数量时不进行计数。 For example, if the string "the white queen" is matched against the pattern the ((?:red|white) (king|queen)) the captured substrings are "white queen" and "queen", and are numbered 1 and 2. 例如,如果字符串“白色皇后”与模式匹配,则捕获的子字符串((?:red | white)(king | queen))为“白色皇后”和“女王”,并分别编号为1和2 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM