我试图将一个字符串拆分为子字符串,按“AND”术语拆分,然后再进行拆分 清除每个子字符串中的“垃圾”。
以下代码出现错误:
AttributeError: 'NoneType' object has no attribute 'group'
import re
def fun(self, str):
for subStr in str.split('AND'):
p = re.compile('[^"()]+')
m = p.match(subStr)
print (m.group())
最佳答案
表示未找到匹配
,返回None
。
请注意,您可能希望在此处使用 re.search
而不是 re.match
。 re.match
仅在字符串的开头匹配,而 re.search
可以搜索字符串中的任何位置。
来自 docs :
Python offers two different primitive operations based on regular expressions:
re.match()
checks for a match only at the beginning of the string, whilere.search()
checks for a match anywhere in the string (this is what Perl does by default).
如果您已经知道,那么您可以使用以下方法处理None
:
if m:
print (m.group())
else:
#do something else
关于python - 使用 REGEX 分割字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17557006/