【发布时间】:2012-06-19 12:25:14
【问题描述】:
我想知道python中是否存在以下任何一种:
- A:非正则表达式等效于“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()。非常感谢任何帮助和/或建议!
【问题讨论】:
-
(B:) re.escape 用于正则表达式,但可能有更好的方法 (A)。
-
请从您的描述开始。不提正则表达式,你真正想做什么?
标签: python regex match findall