Regular expression

P

Paul Hemans

I need to extract the quoted text from :
_("get this")

The following works:
re.compile( "_\(['\"]([^'\"]+)['\"]\)" )
However, I don't want to match if there is A-Z or a-z or 0-9 or _
immediately preceding the "_" so I have tried:
"[^0-9a-zA-Z]*_\(['\"]([^'\"]+)['\"]\)"
"[^\w]{0,1}_\(['\"]([^'\"]+)['\"]\)"
"\W*_\(['\"]([^'\"]+)['\"]\)"

to match against:
skip this text _("get this")

Thanks
 
M

MRAB

I need to extract the quoted text from :
_("get this")

The following works:
re.compile( "_\(['\"]([^'\"]+)['\"]\)" )
However, I don't want to match if there is A-Z or a-z or 0-9 or _
immediately preceding the "_" so I have tried:
"[^0-9a-zA-Z]*_\(['\"]([^'\"]+)['\"]\)"
"[^\w]{0,1}_\(['\"]([^'\"]+)['\"]\)"
"\W*_\(['\"]([^'\"]+)['\"]\)"

to match against:
skip this text _("get this")
Use a negative lookbehind:

re.compile(r'''(?<!\w)_\(['"]([^'"]+)['"]\)''')
 
J

John Bond

I need to extract the quoted text from :
_("get this")

The following works:
re.compile( "_\(['\"]([^'\"]+)['\"]\)" )
However, I don't want to match if there is A-Z or a-z or 0-9 or _
immediately preceding the "_" so I have tried:
"[^0-9a-zA-Z]*_\(['\"]([^'\"]+)['\"]\)"
"[^\w]{0,1}_\(['\"]([^'\"]+)['\"]\)"
"\W*_\(['\"]([^'\"]+)['\"]\)"

to match against:
skip this text _("get this")
Use a negative lookbehind:

re.compile(r'''(?<!\w)_\(['"]([^'"]+)['"]\)''')

Slightly improved version that doesn't allow mixed quotes, eg. __("fred') :

re.compile(r'''(?<!\w)_\((['"])([^'"]+)\1\)''')

The starting quote is now captured as group 1, and has to terminate the
string too (use of \1).

Cheers, JB
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,074
Latest member
StanleyFra

Latest Threads

Top