带逗号的正则表达式搜索>>

问题描述 投票:-1回答:2

需要有关正则表达式的帮助。

str = 'label1 a1,832,b2 and label2 2, c45'

试图返回结果为

['label a1',label 832','label b2','label 2', 'label c45']

到目前为止只能获得['label2 a1','label2 2']

谢谢!

编辑:

为澄清。

我有标签列表

labelList = ['dog','cat','mouse',...]

str = 'There are 3 locations which are dog 122, h25 and cat a3.'

结果应该是:

result = 'dog 122', 'dog h25' and 'cat a3'.

目前,我正在像这样进行正则表达式搜索:

for x in labelList:
    re.search(r'\b(%s) ([^ \r\n]+\b')

希望这可以澄清问题!

edit2:

labelList = ['dog','cat','mouse',...]

str = 'There are 3 locations which are dog 122, h25 and cat a3.'

for x in labelList:

    if re.search(r'\b(%s)\b' % (x), str):

        nr = [f"(%s) {m}" % (x) for m in re.findall(r"(?:(%s))?(\w+)",  comText) if m!= 'and']
        print(nr)

但是,输出似乎是错误的。它给了我以下输出

["(dog) (' ','there')", "(dog) (' ','are')", "(dog) (' ', '3')" ... 

需要有关正则表达式的帮助。到目前为止,str ='label1 a1,832,b2和label2 2,c45'尝试返回结果为['label a1',label 832','label b2','label 2','label c45'] ...

python regex search
2个回答
0
投票

尝试这个:


0
投票

好的。到目前为止,我已经有一种方法可以提取其中一个标签之后的文本,直到一个句点或单词“ and”。

© www.soinside.com 2019 - 2024. All rights reserved.