zl程序教程

您现在的位置是:首页 >  后端

当前栏目

9 python 匹配开头和结尾

Python 匹配 开头 结尾
2023-06-13 09:12:45 时间

大家好,又见面了,我是你们的朋友全栈君。

1. 匹配开头和结尾

代码 功能 ^ 匹配字符串开头 $ 匹配字符串结尾 示例1:^ 需求:匹配以数字开头的数据

import re

# 匹配以数字开头的数据
match_obj = re.match("^\d.*", "3hello")
if match_obj:
    # 获取匹配结果
    print(match_obj.group())
else:
    print("匹配失败")

运行结果:

3hello 示例2:$ 需求: 匹配以数字结尾的数据

import re
# 匹配以数字结尾的数据
match_obj = re.match(".*\d$", "hello5")
if match_obj:
    # 获取匹配结果
    print(match_obj.group())
else:
    print("匹配失败")

运行结果:

hello5 示例3:^ 和 $ 需求: 匹配以数字开头中间内容不管以数字结尾

match_obj = re.match("^\d.*\d$", "4hello4")
if match_obj:
    # 获取匹配结果
    print(match_obj.group())
else:
    print("匹配失败")

运行结果:

4hello4

2.除了指定字符以外都匹配

需求: 第一个字符除了aeiou的字符都匹配

import re


match_obj = re.match("[^aeiou]", "h")
if match_obj:
    # 获取匹配结果
    print(match_obj.group())
else:
    print("匹配失败")

执行结果

h

3. 小结

^ 表示匹配字符串开头 $ 表示匹配字符串结尾

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/159980.html原文链接:https://javaforall.cn