2014-09-27 61 views
0

我試圖得到一個正則表達式的工作,我有問題: 我想匹配與正則表達式爲__(「...」)

__(' or __(" 

和結束一切開始與

') or ") 

我試着用

/__\(['"][^']*['"]\)/g and /__\(['"].*['"]\)/g 

,但它們都與此示例文本的問題:

text that should not match 
__('all text and html<a href="#">link</a> that should match') text that should not match __('all text and html<a  href="#">link</a>') 
__("all text and html<a href="#">link</a>") text that should not match __("all text and html<a  href="#">link</a>") 
other text that should not match 

誰贏了RegExp?

回答

0

使用第二個示例,使用*?進行非貪婪匹配,並考慮使用引號的反向引用。

/__\((['"]).*?\1\)/g 

Live Demo

+0

一個非貪婪的匹配('?')可能會有所幫助,儘管我們還不知道這個問題。 – 2014-09-27 19:48:14

+0

非常感謝!就是這個! – blockwork 2014-09-27 20:59:47

0

我猜你要非貪婪匹配,那麼最好的解決辦法是使用:

/__\(['"][^']*?['"]\)/g 

此外,逃逸單引號和雙引號可以幫助:

您可以在此regex10查看

http://regex101.com/r/sM8yF9/1