Python:re.findall的非正则表达式等价物



我想知道python中是否存在以下任何内容:

  • 答:非正则表达式等价于"re.findall()"。
  • B:一种在传递给 findall() 之前中和变量中的正则表达式特殊字符的方法。

我正在将一个变量传递给 re.findall,当变量有句点、斜杠或克拉等时会遇到问题,因为我希望这些字符从字面上解释。我意识到没有必要使用正则表达式来完成这项工作,但我喜欢 re.findall() 的行为,因为它返回它找到的每个匹配项的列表。 这使我可以使用len()轻松计算子字符串存在的次数。

这是我的代码示例:

>>substring_matches = re.findall(randomVariableOfCharacters, document_to_be_searched)
>>
>>#^^ will return something like ['you', 'you', 'you']
>>#but could also return something like ['end.', 'end.', 'ends']
>>#if my variable is 'end.' because "." is a wildcard.
>>#I would rather it return ['end.', 'end.']
>>
>>occurrences_of_substring = len(substring_matches)

如果可能的话,我希望不必使用 string.find()。 任何帮助和/或建议将不胜感激!

如果你只想要出现次数,你可以使用 str.count(),但它不等同于 re.findall(),它只获取计数。

document_to_be_searched = "blabla bla bla."
numOfOcur = document_to_be_searched.count("bl")

当然:看看你的代码,我认为你正在寻找的是string.count.

>>> 'abcdabc'.count('abc')
2

但是请注意,这并不等同于re.findall;尽管它看起来更适合您的情况。

最新更新