在字符串中查找多个子字符串,这些子字符串略有不同

2024-06-16 11:23:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试解析各种类似这样的字符串

cpd00015\U c+cpd00041\U c+cpd00095\U c-->;2.0 cpd00001\U c+cpd00009\U c+cpd00067\U c

现在我有一些代码可以找到第一个实例,但是我想找到这些实例的所有实例。你知道吗

try:
found = re.search('cpd(.+?)_c', reactionEquation).group(1)
print(found)
except AttributeError:
# AAA, ZZZ not found in the original string
pass # apply your error handling

那个检索函数只查找此的第一个实例。有没有研究过你不完全知道名字的多个字符串?你知道吗


Tags: 实例字符串代码gtresearchtryfound
2条回答

要获取所有匹配项,请使用re.findall

例如:

import re
s = "cpd00015_c + cpd00041_c + cpd00095_c  > 2.0 cpd00001_c + cpd00009_c + cpd00067_c"
print( re.findall("cpd(.+?)_c", s) )

输出:

['00015', '00041', '00095', '00001', '00009', '00067']

只需将search更新为find all并删除组。你知道吗

import re
try:
    found_all = re.findall('cpd(.+?)_c', reactionEquation)
    for found in found_all : 
        print(found)
except AttributeError:
    # AAA, ZZZ not found in the original string
    pass # apply your error handling

相关问题 更多 >