Python教学:使用Python及正则表达式进行小数的检测的两种方法

 第一部分:

方法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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

gCodeTop 格码拓普 老师

您的鼓励.我的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值