第一部分:
方法1:
import re
# A.可以识别: .233,3.,3.344,566等类型的数据
s = "12.aa"
ret = re.match(r'\d*\.?\d*', s)
# print(ret)
if(ret==None):
print("Err")
else:
if ret.group(0)!=s or ret.group(0)=='':
print("Err")
else:
print("OK")
方法2:
import re
# B.可以识别: 1.233,3.2, 3.344,566 等类型的数据
s2 = "12.aa"
ret2 = re.match(r'\d+\.?\d+|\d', s2)
# print(ret)
if(ret2==None):
print("Err")
else:
if ret2.group(0)!=s2:
print("Err")
else:
print("OK")
综合练习应用:
第二部分:
import re
date_str = "2023-05-15 aaa"
date_pattern = r"(\d{4})-(\d{2})-(\d{2})"
match = re.match(date_pattern, date_str)
print(match)
if match:
print("完整日期:", match.group(0))
print("年:", match.group(1))
print("月:", match.group(2))
print("日:", match.group(3))
print("所有分组:", match.groups()) # 返回所有分组的元组
第三部分:
Python中re.match返回None的示例
re.match()
在Python中用于从字符串开头匹配正则表达式,当匹配失败时会返回None。以下是几种常见返回None的情况:
1. 字符串开头不匹配模式
python
import re
result = re.match(r'\d+', 'abc123') # 开头不是数字
print(result) # 输出: None
2. 模式要求字符串开头有特定内容但实际没有
python
result = re.match(r'^Hello', 'Hi, Hello') # 虽然字符串包含Hello但不是开头
print(result) # 输出: None
3. 大小写不匹配(未使用忽略大小写标志)
python
result = re.match(r'python', 'Python') # 大小写不匹配
print(result) # 输出: None
# 使用re.IGNORECASE可以匹配
result = re.match(r'python', 'Python', re.IGNORECASE)
print(result) # 输出: <re.Match object; span=(0, 6), match='Python'>
4. 模式过于严格
python
result = re.match(r'\d{4}-\d{2}-\d{2}', '2023/05/15') # 分隔符不匹配
print(result) # 输出: None
5. 空字符串匹配非可选模式
python
result = re.match(r'\w+', '') # 空字符串无法匹配\w+
print(result) # 输出: None
6. 使用match但期望在字符串中间匹配
python
result = re.match(r'world', 'hello world') # match只在开头匹配
print(result) # 输出: None
# 应该使用re.search来查找字符串中的匹配
result = re.search(r'world', 'hello world')
print(result) # 输出: <re.Match object; span=(6, 11), match='world'>
检查返回值是否为None的常用方式
python
pattern = r'\d+'
string = 'abc123'
match = re.match(pattern, string)
if match is None:
print("没有找到匹配")
else:
print("找到匹配:", match.group())
注意:re.match()
只在字符串开头进行匹配,如果需要在字符串任意位置查找匹配,应使用re.search()
。