简体   繁体   中英

Python Regex Get String Between Two Substrings

First off, I know this may seem like a duplicate question, however, I could find no working solution to my problem.

I have string that looks like the following:

string = "api('randomkey123xyz987', 'key', 'text')"

I need to extract randomkey123xyz987 which will always be between api(' and ',

I was planning on using Regex for this, however, I seem to be having some trouble.

This is the only progress that I have made:

import re
string = "api('randomkey123xyz987', 'key', 'text')"
match = re.findall("\((.*?)\)", string)[0]
print match

The following code returns 'randomkey123xyz987', 'key', 'text'

I have tried to use [^'] , but my guess is that I am not properly inserting it into the re.findall function.

Everything that I am trying is failing.


Update: My current workaround is using [2:-4] , but I would still like to avoid using match[2:-4] .

If the string contains only one instance, use re.search() instead:

>>> import re
>>> s = "api('randomkey123xyz987', 'key', 'text')"
>>> match = re.search(r"api\('([^']*)'", s).group(1)
>>> print match
randomkey123xyz987

You want the string between the ( and , , you are catching everything between the parens:

match = re.findall("api\((.*?),", string)

print match 
["'randomkey123xyz987'"]

Or match between the '' :

match = re.findall("api\('(.*?)'", string)
print match 
['randomkey123xyz987']

If that is how your strings actually look you can split:

string = "api('randomkey123xyz987', 'key', 'text')"

print(string.split(",",1)[0][4:])

You should use the following regex:

api\('(.*?)'

Assuming that api( is fixed prefix

It matches api( , then captures what appears next, until ' token.

>>> re.findall(r"api\('(.*?)'", "api('randomkey123xyz987', 'key', 'text')")
['randomkey123xyz987']

If you are certain that randomkey123xyz987 will always be between "api('" and "',", then using the split() method can get it done in one line. This way you will not have to use regex matching. It will match the pattern between the starting and ending delimiter which is "api('" and "', ".

>>> string = "api('randomkey123xyz987', 'key', 'text')"
>>> value = (string.split("api('")[1]).split("',")[0]
>>> print value
randomkey123xyz987

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