简体   繁体   中英

Python Regular expression to extract a substring

I have a string

" request.addParameter('page','/TMRMKUOHY/RPM/Store/srrreVkew.jsp?resODFlag','N','',true,false); " .

I want to extract the part

" '/TMRMKUOHY/RPM/Store/srrreVkew.jsp?resODFlag' "

out of this string. I tried several combinations of regex (using re module in python) but can't find the exact desired pattern that gives me the substring out of the main string.

'([^']+)'

You can try this.

Do print re.findall(r"'([^']+)'",x)[1] .

Here x is your string.Basically it is extracting the second group.

See demo.

http://regex101.com/r/yG7zB9/2

Use the regex

'\/[^']+'

The code can be written as

x="  request.addParameter('page','/TMRMKUOHY/RPM/Store/srrreVkew.jsp?resODFlag','N','',true,false); ".
re.findall(r"'\/[^']+'", x)"
["'/TMRMKUOHY/RPM/Store/srrreVkew.jsp?resODFlag'"]

see how the regex works http://regex101.com/r/pK9mI8/1

you can also use search function to search and find the substring matching the pattern as

 re.search(r"'\/[^']+'", x).group()
"'/TMRMKUOHY/RPM/Store/srrreVkew.jsp?resODFlag'"

Seems like you want something like this,

>>> import re
>>> s = "  request.addParameter('page','/TMRMKUOHY/RPM/Store/srrreVkew.jsp?resODFlag','N','',true,false); "
>>> re.search(r"'(/[^']*)'", s).group(1)
'/TMRMKUOHY/RPM/Store/srrreVkew.jsp?resODFlag'

You are not forced to use regex you can use split() :

>>> s.split(',')[1]
"'/TMRMKUOHY/RPM/Store/srrreVkew.jsp?resODFlag'"

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