【问题标题】:Error AttributeError: 'NoneType' object has no attribute 'group'错误 AttributeError:“NoneType”对象没有属性“组”
【发布时间】: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


    【解决方案1】:

    match

    如果字符串开头的零个或多个字符匹配 正则表达式模式,返回对应的匹配对象。 如果字符串与模式不匹配,则返回None;请注意,这 不同于零长度匹配。

    所以你应该使用is None检查在不匹配时考虑大小写,考虑以下简单示例

    import re
    texts = ["123abc","456","def"]
    compiled = re.compile(r'([0-9]+)')
    for t in texts:
        match = compiled.match(t)
        if match is None:
            print('No leading digits found')
        else:
            print('Leading digits are', match.group(1))
    

    输出

    Leading digits are 123
    Leading digits are 456
    No leading digits found
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-10
      • 2019-07-18
      • 2018-01-27
      • 1970-01-01
      相关资源
      最近更新 更多