Python正则表达式获取两个子字符串之间的字符串 [英] Python Regex Get String Between Two Substrings
问题描述
首先,我知道这可能看起来像一个重复的问题,但是,我找不到解决我的问题的可行解决方案.
我有如下所示的字符串:
string = "api('randomkey123xyz987', 'key', 'text')"
我需要提取 randomkey123xyz987,它总是在 api(' 和 ',
之间我打算为此使用 Regex,但是,我似乎遇到了一些麻烦.
这是我取得的唯一进步:
导入重新string = "api('randomkey123xyz987', 'key', 'text')"match = re.findall("\((.*?)\)", string)[0]打印匹配
以下代码返回'randomkey123xyz987', 'key', 'text'
我尝试使用 [^'],但我的猜测是我没有正确地将它插入到 re.findall 函数中.
我尝试的一切都失败了.
<小时>更新:我目前的解决方法是使用 [2:-4],但我仍然想避免使用 match[2:-4].
如果字符串只包含一个实例,使用 re.search()
代替:
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
这篇关于Python正则表达式获取两个子字符串之间的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!