1、编程试题:
编写一个程序,使用正则表达式检查字符串是否与给定模式匹配。
定义函数check_regex_match(),该函数接受两个字符串参数,input_string和pattern。
在函数中,使用Python内置的re模块来实现支持.和*的正则表达式匹配。
如果找到匹配,则返回True,否则返回False。
这里,我们使用正则表达式来检查字符串是否与特定模式匹配。 点.匹配任何单个字符,星号*匹配前面字符的0个或多个出现。
示例输入
abaaa
a.a*
示例输出
True
解释:
点.匹配b,星号*匹配aaa。
2、代码实现:
可编辑代码如下:
#!/usr/bin/python3.9
# -*- coding: utf-8 -*-
#
# Copyright (C) 2024 , Inc. All Rights Reserved
#
# @Time : 2024/3/10 19:35
# @Author : fangel
# @FileName : 148. 正则表达式匹配.py
# @Software : PyCharm
import re
def check_regex_match(input_string, pattern):
matchtype = re.fullmatch(pattern, input_string)
if isinstance(matchtype, re.Match):
return True
else:
return False
input_string = input()
pattern = input()
print(check_regex_match(input_string, pattern))
3、代码分析:
当且仅当整个字符串与模式匹配时,re.fullmatch()返回一个匹配对象。否则,返回None。
本例根据匹配对象是否是re.Match的实例即可
4、运行结果:
输入:
aba
a.a
输出:
True