python

时间:2018-02-13 18:33:22

标签: python regex

我正在做家庭作业,我需要使用正则表达式在另一个名为lorem_ipsum的较大字符串中查找各种字符和字符串,我一直得到TypeError:期望的字符串或缓冲区,指定lorem_ipsum是一个不是列表的字符串所以这不是问题。 这些是我写的两个代码: 这个是在lorem_ipsum中查找所有非字母数字字符,并输出它们出现的次数,它应该返回144:

string1 = len(lorem_ipsum)
pattern = "^[[]]"
matches1 = re.match(pattern, string1)
results = matches1.read()

这个是找到lorem_ipsum中所有出现的情况,并输出它们出现的次数,它应该输出3:

string1 = len(lorem_ipsum)
pattern = "sit[-:]amet"
matches1 = re.findall(pattern, string1)
results = matches1.count(pattern, string1)

print (results)

我之前从未遇到过这个问题,据我所知,我使用的语法与之前的作业相同。

1 个答案:

答案 0 :(得分:0)

您的问题是代码第2行len()周围的lorem_ipsum

len()会给你一个整数字符串的长度,考虑到正则表达式只需要一个字符串或缓冲区,我认为这不是你想要匹配的。删除len所以第2行看起来像这样:

matches1 = re.match(pattern, lorem_ipsum)