[英]check if regex contains a capturing group
I working on a routing system and i want to allow custom regex patterns. 我在路由系统上工作,我想允许自定义正则表达式模式。 My question is how can i detect if a regex contains a capturing group? 我的问题是如何检测正则表达式是否包含捕获组?
So for example the pattern [0-9]+
would work, because it doesnt contain a capturing group. 因此,例如模式[0-9]+
将起作用,因为它不包含捕获组。 The pattern ([0-9]+)
would not work. 模式([0-9]+)
不起作用。
It tried to ltrim
and rtrim
the pattern by the (
and )
character mask, this would work with patterns that start with a capturing group like ([A-Za-z]+)
and ([0-9]+)
. 它试图通过(
和)
字符掩码来ltrim
和rtrim
图案,这将适用于以([A-Za-z]+)
和([0-9]+)
类的捕获组开头的图案。 But with patterns that contain a capturing group elsewhere this would not work. 但是,如果在其他地方包含捕获组的模式不起作用。 So how could i check if the pattern contains a capturing group? 那么我如何检查模式是否包含捕获组?
First you should match and omit any escaped characters from results then check if there is any opening bracket remained alone or is followed by ?P<
, ?'
首先,您应该匹配结果并从结果中忽略所有转义的字符,然后检查是否有单独的左括号或后面跟着?P<
?'
or ?<
. 或?<
。 These are opening syntax of a named capturing group. 这些是命名捕获组的开放语法。
\\.(*SKIP)(?!)|\((?(?=\?)\?(P?['<]\w+['>]))
PHP: PHP:
if (preg_match("~\\\\.(*SKIP)(?!)|\((?(?=\?)\?(P?['<]\w+['>]))~", $regex)) {
// Capturing group found
}
RegEx Explanation: RegEx说明:
\\. # Match any escaped character
(*SKIP)(?!) # Skip over and omit recent match
| # OR
\( # Match a single `(`
(?(?=\?) # Which if is followed by `?`
\? #
P?['<]\w+['>] # Next characters should be matched as ?P'name', ?<name> or ?'name'
) # End of conditional statement
I think you want to see if there are capturing groups eg (something)
that are not at the start of the test pattern. 我认为您想查看是否存在不在测试模式开始的捕获组(something)
例如(something)
。 This seems to work for me... 这似乎对我有用...
$pattern = '/^.+\(([^\)]+)\)/';
if (preg_match($pattern, $testpattern)) {
// Capturing group found that is not at the start of the string
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.