[英]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.