简体   繁体   中英

Regular expression for __(' … ')

I'm trying to get a regular expression to work and I'm having problems: I want to match everything that starts with

__(' or __("  

and ends with

') or ") 

I tried with

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

but they all have problems with this sample text:

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

who has the winning RegExp?

Using the second example, use *? for a non-greedy match and consider using a backreference for the quotes.

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

Live Demo

I guess that you want non-greedy match, then the best solution is to use:

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

Also, escaping the single and double quotes may help:

You can check it at this regex101

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM