Python 判断字符串是否以正则表达式开头
可以使用 re 模块的 match() 函数来判断字符串是否以正则表达式开头。下面是一个示例代码:
import re
def is_start_with_regex(string, regex):
pattern = re.compile(regex)
match = pattern.match(string)
return bool(match)
# 示例用法
string = 'abc123'
regex = r'^[a-z]+'
result = is_start_with_regex(string, regex)
print(result) # 输出 True
regex = r'^[0-9]+'
result = is_start_with_regex(string, regex)
print(result) # 输出 False
在上面的示例代码中,is_start_with_regex() 函数接受两个参数,分别是待判断的字符串和正则表达式。函数内部使用 re 模块的 compile() 函数将正则表达式编译成模式对象,然后调用 match() 函数来进行匹配。最后,将匹配结果转换为布尔值返回。
原文地址: https://www.cveoy.top/t/topic/p5qu 著作权归作者所有。请勿转载和采集!