首页 > 解决方案 > 在 Python 中使用 AND 条件查找两个模式之间的字符串

问题描述

我想识别两个模式之间的字符串(lettre/例如,“和”)。此外,识别的字符串不应该对应于第三个模式(somth?other例如)。

在 MAC OSX 10.13 上运行的 Python 3.7

import re
strings = ['lettre/abc"','lettre/somth?other"','lettre/acc"','lettre/edf"de','lettre/nhy"','lettre/somth?other"']

res0_1 = re.search('lettre/.*?\"', strings[0])
res1_1 = re.search('lettre/.*?\"', strings[1])
print(res0_1)
<re.Match object; span=(0, 11), match='lettre/abc"'>
print(res1_1)
<re.Match object; span=(0, 19), match='lettre/somth?other"'>

res0_2 = re.search('lettre/(.*?\"&^[somth\?other])', strings[0])
res1_2 = re.search('lettre/(.*?\"&^[somth\?other])', strings[1])
print(res0_2)
None
print(res1_2)
None

我想得到res0_1forstrings[0]res1_2for strings[1]

标签: pythonregexpython-3.xsearch

解决方案


据我了解试试这个:

import re
strings = ['lettre/abc"','lettre/somth?other"','lettre/acc"','lettre/edf"de','lettre/nhy"','lettre/somth?other"']

res0_1 = re.findall('lettre/(.*)\"', strings[0])
res1_2 = re.findall('lettre/(.*)\"', strings[1])
print(res0_1)
print(res1_2)

希望能帮助到你


推荐阅读