[英]check if regex contains a capturing group
我在路由系统上工作,我想允许自定义正则表达式模式。 我的问题是如何检测正则表达式是否包含捕获组?
因此,例如模式[0-9]+
将起作用,因为它不包含捕获组。 模式([0-9]+)
不起作用。
它试图通过(
和)
字符掩码来ltrim
和rtrim
图案,这将适用于以([A-Za-z]+)
和([0-9]+)
类的捕获组开头的图案。 但是,如果在其他地方包含捕获组的模式不起作用。 那么我如何检查模式是否包含捕获组?
首先,您应该匹配结果并从结果中忽略所有转义的字符,然后检查是否有单独的左括号或后面跟着?P<
?'
或?<
。 这些是命名捕获组的开放语法。
\\.(*SKIP)(?!)|\((?(?=\?)\?(P?['<]\w+['>]))
PHP:
if (preg_match("~\\\\.(*SKIP)(?!)|\((?(?=\?)\?(P?['<]\w+['>]))~", $regex)) {
// Capturing group found
}
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
我认为您想查看是否存在不在测试模式开始的捕获组(something)
例如(something)
。 这似乎对我有用...
$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.