温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

40 python 正则表达式 match方法匹配字符串 使

发布时间:2020-05-23 04:38:00 来源:网络 阅读:434 作者:马吉辉 栏目:大数据
第一课: 使用match方法匹配字符串
# 正则表达式:使用match方法匹配字符串

'''
正则表达式:是用来处理文本的,将一组类似的字符串进行抽象,形成的文本模式字符串

windows dir *.txt   file1.txt  file2.txt  abc.txt  test.doc
a-file1.txt-b
linux/mac ls

主要是学会正则表达式的5方面的方法
1. match:检测字符串是否匹配正则表达式
2. search:在一个长的字符串中搜索匹配正则表达式的子字符串
3. findall:查找字符串
4. sub和subn:搜索和替换
5. split: 通过正则表达式指定分隔符,通过这个分隔符将字符串拆分
'''

import re      # 导入正则表达的模块的 

m = re.match('hello', 'hello') # 第一个指定正则表达式的字符串,第二个表示待匹配的字符串 实际上 正则表达式也可以是一个简单的字符串

print(m)    # <re.Match object; span=(0, 5), match='hello'>

print(m.__class__.__name__)  # 看一下m的类型 Match
print(type(m))                  # <class 're.Match'> 

m = re.match('hello', 'world')
if m is not None:
    print('匹配成功')
else:
    print('匹配不成功')

# 待匹配的字符串的包含的话正则表达式,系统也认为是不匹配的
m = re.match('hello', 'world hello')
print(m)    # None  如果不匹配的话,返回值为None

# 待匹配的字符串的前缀可以匹配正则表达式,系统也认为是匹配的
m = re.match('hello', 'hello world')
print(m)  # <re.Match object; span=(0, 5), match='hello'>

----------------------------------------------
第二课 正则中使用search函数在一个字符串中查找子字符串

# search函数 和 match函数的区别是,search函数中 字符串存在就可以匹配到,match函数 必须要 前缀可以匹配正则表达式,系统也认为是匹配的 

import re

m = re.match('python', 'I love python.')
if m is not None:
    print(m.group())    # 调用group的方法就是返回到一个组里面
print(m)            # None
m = re.search('python', 'I love python.')
if m is not None:
    print(m.group())
print(m)  
#
# python
# <re.Match object; span=(7, 13), match='python'>  
span=(7, 13) 表示 python在 'I love python.' 字符串中的位置 
左闭右开
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI