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

第一课: 使用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) #

print(m.__class__.__name__) # 看一下m的类型 Match

print(type(m)) #

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) #

----------------------------------------------

第二课 正则中使用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

#

span=(7, 13) 表示 python在 'I love python.' 字符串中的位置

左闭右开

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值