2014-10-28 44 views
1

在我正則表達式如下構造,正則表達式正向前查找故障

<([A-Z][A-Z0-9]*)\b[^>]*>(.*?)</\1> will match the opening and closing pair of any HTML tag, while 

q(?=(<([A-Z][A-Z0-9]*)\b[^>]*>(.*?)</\1>)) this positive lookahead construct should match every q followed by a pair of any HTML tag. 

下面的函數返回null。但我認爲它不應該。

function regex($detail) 
{ 
    if(preg_match('#q(?=(<([A-Z][A-Z0-9]*)\b[^>]*>(.*?)</\1>))#i', $detail)) 
    { 
     return true; 
    } 
    return false;  
} 

$detail = 'q<p>is this my first post is this my first post is this my first post is this my first post is this</p>'; 
echo regex($detail); 

但是這種結構下驗證

q(?=(regex)) 

我希望如果我正則表達式的功能結構中的任何錯誤可以指出。

回答

3

您的反向引用是指錯誤的組。它應該是指1

'#q(?=(<([A-Z][A-Z0-9]*)\b[^>]*>(.*?)</\2>))#i' 
    ^^   ^    ^
     | 2--------------2     | 
     1-----------------------------------1 
+0

拼命但這方式更簡單的傳達點+1: ) – vks 2014-10-28 15:36:51

+0

+1對於OP的正則表達式優秀的視覺顯示問題 – anubhava 2014-10-28 15:43:25

2
q(?=(<([A-Z][A-Z0-9]*)\b[^>]*>(?:.*?)<\/\2>)) 

你搞亂UO與grouping.Try這2組而不是組。 \1與您所期望的不同。

查看演示。

http://regex101.com/r/sU3fA2/31

如果你不抓住拳頭組,你的正則表達式將工作fine.See

q(?=(?:<([A-Z][A-Z0-9]*)\b[^>]*>(.*?)<\/\1>)) 

http://regex101.com/r/sU3fA2/32

+0

+1好的答案... – anubhava 2014-10-28 15:44:09

+0

@anubhava thanx :) – vks 2014-10-28 15:46:36