繁体   English   中英

python-提取特定的字符串

[英]python - to extract a specific string

我有一个像这样的字符串:

    string="(tag, index: develop-AB123-2s), (index: develop-CD123-2s)"

我只想提取“ develop-CD123-2s”,即“(index:”之后的字符串,而不是带有标签的字符串。我该如何在python中做呢?

警告:我不是正则表达式的佼佼者

import re
s='(tag, index: develop-AB123-2s), (index: develop-CD123-2s)'
print re.findall("\\(.*?index: ([^)]+)", s)[1]  # 'develop-CD123-2s'

正则表达式演示

替代正则表达式

re.findall("index: ([^\s)]+)", s)[1]
>>> string.split("), (")[1].split(":")[1].split(")")[0].strip()
'develop-CD123-2s'
>>> 

第一个拆分将每个元组分开,然后在:上拆分并获取第二个结果

您可以这样做:

string = "(tag, index: develop-AB123-2s), (index: develop-CD123-2s)"

string = string.split('(index:')
string = string[1].strip(')')
print(string)

将字符串分割为(index:并去除右花括号

一种方法是使用python regex- 肯定的后置断言

import re
string = "(tag, index: develop-AB123-2s), (index: develop-CD123-2s)"
re.findall(r"(?<=\(index:) ([^)]+)", string)

此模式仅匹配以(index: :。开头的内容。您还可以查看断言背后的否定式隐喻,以尝试与(tag, part。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM