2013-05-13 52 views
1

看看這個正則表達式:正則表達式的結束標記=啓動標籤

(?:\(?")(.+)(?:"\)?) 

此正則表達式將匹配例如

"a" 
("a") 

而且 「一)

我怎樣才能說起始字符[在這種情況下「或」)與結束字符相同?必須有一個比這更簡單的解決方案,對吧?

"(.+)"|(?:\(")(.+)(?:"\)) 

回答

1

我不認爲有這樣做特別是與正則表達式的好方法,讓你堅持做這樣的事情:

/(?: 

"(.+)" 
| 
\((.+) \) 

)/x 
1

怎麼樣:

(\(?)(")(.+)\2\1 

解釋:

(?-imsx:(\(?)(")(.+)\2\1) 

matches as follows: 

NODE      EXPLANATION 
---------------------------------------------------------------------- 
(?-imsx:     group, but do not capture (case-sensitive) 
         (with^and $ matching normally) (with . not 
         matching \n) (matching whitespace and # 
         normally): 
---------------------------------------------------------------------- 
    (      group and capture to \1: 
---------------------------------------------------------------------- 
    \(?      '(' (optional (matching the most amount 
          possible)) 
---------------------------------------------------------------------- 
)      end of \1 
---------------------------------------------------------------------- 
    (      group and capture to \2: 
---------------------------------------------------------------------- 
    "      '"' 
---------------------------------------------------------------------- 
)      end of \2 
---------------------------------------------------------------------- 
    (      group and capture to \3: 
---------------------------------------------------------------------- 
    .+      any character except \n (1 or more times 
          (matching the most amount possible)) 
---------------------------------------------------------------------- 
)      end of \3 
---------------------------------------------------------------------- 
    \2      what was matched by capture \2 
---------------------------------------------------------------------- 
    \1      what was matched by capture \1 
---------------------------------------------------------------------- 
)      end of grouping 
+0

是的,有在PHP反向引用,但TC不想匹配'(「a」('所以它不在這個例子中工作。 – dognose 2013-05-13 10:50:39

0

您可以在PHP中使用佔位符。但要注意,這是不正常的正則表達式的行爲,其特殊到PHP:

preg_match("/<([^>]+)>(.+)<\/\1>/")(該\1參照第1場比賽的結果)

這將使用第一個匹配的條件收盤匹配。這匹配<a>something</a>但不是<h2>something</a>

然而,在你的情況下,你需要把第一組中的「(」匹配成「)」 - 這將無法正常工作。

更新:將()更換爲<BRACE><END_BRACE>。然後你可以使用/<([^>]+)>(.+)<END_\1>/匹配。爲所有需要的元素執行此操作:()[]{}<>和whatevs。

(a) is as nice as [f]將成爲<BRACE>a<END_BRACE> is as nice as <BRACKET>f<END_BRACKET>和正則表達式將捕獲兩種,如果你使用preg_match_all

$returnValue = preg_match_all('/<([^>]+)>(.+)<END_\\1>/', '<BRACE>a<END_BRACE> is as nice as <BRACKET>f<END_BRACKET>', $matches); 

導致

array (
    0 => 
    array (
    0 => '<BRACE>a<END_BRACE>', 
    1 => '<BRACKET>f<END_BRACKET>', 
), 
    1 => 
    array (
    0 => 'BRACE', 
    1 => 'BRACKET', 
), 
    2 => 
    array (
    0 => 'a', 
    1 => 'f', 
), 
)