【发布时间】:2022-07-20 20:25:24
【问题描述】:
我编写了这段代码来搜索字符串。我在正则表达式中创建了条件,所以我可能有括号之间的内容是should,外面是must,而前面的内容是must not。
但是如果列表为空怎么办?我的意思是如果消息没有() 也没有- 我该如何处理?
重新导入
message='read read read'
others = ' '.join(re.split('\(.*\)', message))
others_split = others.split()
to_compile = re.compile('.*\((.*)\).*')
to_match = to_compile.match(message)
ors_string = to_match.group(1)
should = ors_string.split(' ')
must = [term for term in re.findall(r'\(.*?\)|(-?(?:".*?"|\w+))', message) if term and not term.startswith('-')]
must_not = [term for term in re.findall(r'\(.*?\)|(-?(?:".*?"|\w+))', message) if term and term.startswith('-')]
must_not = [s.replace("-", "") for s in must_not]
print(f'must: {must}')
print(f'should: {should}')
print(f'must_not: {must_not}')
想要的结果:
must: ['read', 'read', 'read']
should: []
must_not: []
如何处理这个错误?
Traceback (most recent call last):
File "<string>", line 10, in <module>
AttributeError: 'NoneType' object has no attribute 'group'
【问题讨论】:
标签: python arrays python-3.x regex string