python解析之正则表达式,由浅入深带你轻松学会正则表达式(01基础)

前言:正则不是我们写的,python中正则的解析通过re模块完成

相关函数:

1.match:从开头进行匹配,匹配到就返回正则结果对象,没有返回None。

2.search:从任意位置匹配,功能同上。

3.findall:全部匹配,返回匹配到的内容组成的列表,没有返回空列表。

4.compile:生成正则表达式对象

示例代码:

import re

# 从开头查找,找到返回正则匹配结果对象,没有找到返回None
# m = re.match('abc', 'abcdask;jabcsdajl')
# 从任意位置查找,功能同上
m = re.search('abc', 'shdalsjdabchaoeor')

if m:
    # 返回匹配的内容
    print(m.group())
    # 返回匹配内容位置
    print(m.span())

# 匹配所有内容,找到返回所有匹配的内容列表,没有找到返回空列表
f = re.findall('abcd', 'adsjkjdabcajsdlasabcjsdlaabc')
print(f)

# 先生成正则表达式对象
c = re.compile('hello')
# print(type(c))

# 从开头匹配
m = c.match('hellosadk;ask;kahellosadhlkas')
print(m)

# 从任意位置匹配
s = c.search('hadlsjasdhellokjsdlks')
print(s)

# 匹配所有内容
f = c.findall('hellosdhasdjahelloshdajldhello')
print(f)

运行结果:

猜你喜欢

转载自blog.csdn.net/z_xiaochuan/article/details/81584930