Python Regex Get String Between Two Substrings

别来无恙 提交于 2020-11-28 08:10:47

问题


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].


回答1:


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



回答2:


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:])



回答3:


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']



回答4:


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


来源:https://stackoverflow.com/questions/29703793/python-regex-get-string-between-two-substrings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!