gpt4 book ai didi

python - 确定 Python 对象是正则表达式还是字符串

转载 作者:太空宇宙 更新时间:2023-11-03 13:42:46 24 4
gpt4 key购买 nike

思考练习:编写采用正则表达式模式精确匹配字符串的 Python 函数的“最佳”方法是什么:

import re
strings = [...]

def do_search(matcher):
"""
Returns strings matching matcher, which can be either a string
(for exact match) or a compiled regular expression object
(for more complex matches).
"""
if not is_a_regex_pattern(matcher):
matcher = re.compile('%s$' % re.escape(matcher))

for s in strings:
if matcher.match(s):
yield s

那么,is_a_regex_pattern() 的实现思路是什么?

最佳答案

您可以通过 re._pattern_type 访问 _sre.SRE_Pattern 类型:

if not isinstance(matcher, re._pattern_type):
matcher = re.compile('%s$' % re.escape(matcher))

下面是一个演示:

>>> import re
>>> re._pattern_type
<class '_sre.SRE_Pattern'>
>>> isinstance(re.compile('abc'), re._pattern_type)
True
>>>

关于python - 确定 Python 对象是正则表达式还是字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27365956/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com