python - 使用 REGEX 分割字符串

标签 python regex for-loop split

我试图将一个字符串拆分为子字符串,按“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.matchre.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, while re.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/

相关文章:

matlab - 向量化嵌套的 for 循环和 if 语句

python - 想要计算列中满足条件的值的数量

python - 如何根据日期列更改线图的颜色?

php - 单词的正则表达式

php - 正则表达式匹配带和不带特殊/重音字符的字符串?

用于验证 youtube 嵌入 url 的 javascript 正则表达式

c# - 如何用 C# 中的函数语句替换 for 循环?

python - 是否可以在 OneHotEncoder 中为某些列指定 handle_unknown = 'ignore' 并为其他列指定 'error'?

python - 递归函数内存使用

R 上的重复函数