参考资料

具体内容

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import re

# 简单匹配
pattern1 = "cat"
pattern2 = "bird"
string = "dog runs to cat"
print(pattern1 in string)
print(pattern2 in string)
# True
# False

# 用正则表达式,找到了返回的是对象
print(0)
print(re.search(pattern1, string))
print(re.search(pattern2, string))
# <re.Match object; span=(12, 15), match='cat'>
# None

# 匹配多种可能,[]中表示选其中一个的情况
print(1)
ptn = r"r[au]n"
print(re.search(ptn, string))
# <re.Match object; span=(4, 7), match='ran'>
# <re.Match object; span=(4, 7), match='run'>

# 匹配更多种可能
print(2)
print(re.search(r"r[A-Z]n", string))
# None
print(re.search(r"r[0-9a-z]n", string))
# <re.Match object; span=(4, 7), match='run'>


# 特殊匹配

# 数字
# \d 表示所有数字
# \D 表示所有不是数字
print(3)
print(re.search(r"r\dn", string))
# None
print(re.search(r"r\Dn", string))
# <re.Match object; span=(4, 7), match='run'>

# 空白
# \s 所有的空白符
# \S 所有不是空白符
print(4)
print(re.search(r"r\sn", "r\nn,is..."))
# <re.Match object; span=(0, 3), match='r\nn'>
print(re.search(r"r\Sn", "run,run"))
# <re.Match object; span=(0, 3), match='run'>

# 所有字母数字和"_"
# \w 数字字母和"_"
# \W 除了上述的其他

# 空白字符
# \\ 匹配 \
# . 除了\

# 句尾句首
# ^ 句首
# $ 句尾
print(5)
print(re.search(r"^run", "run,is..."))
# <re.Match object; span=(0, 3), match='run'>
print(re.search(r"run$", "run,is..."))

# 有没有匹配
# ?
print(6)
print(re.search(r"run(pig)?", "runs...runpig"))
# <re.Match object; span=(6, 12), match='runpig'>

# 多行匹配
string = """
dog runs to cat
I run to dog.
"""
print(7)
print(re.search(r"^I", string))
# None
print(re.search(r"^I", string, flags=re.M))
# <re.Match object; span=(22, 23), match='I'>

# 0或多次
print(8)
print(re.search(r"ab*", "ab"))
# <re.Match object; span=(0, 2), match='ab'>
print(re.search(r"ab*", "abbbbb"))
# <re.Match object; span=(0, 6), match='abbbbb'>

# 1次或多次
# +

# 可选次数
# {0,10}

# group组
print(9)
match = re.search(r"(\d+),Date:(.+)", "ID: 021523,Date:Feb/12/2017")
print(match.group())
# 021523,Date:Feb/12/2017
print(match.group(1))
# 021523
print(match.group(2))
# Feb/12/2017
# 可以给定名字
match = re.search(r"(?P<name>\d+),Date:(?P<id>.+)", "ID: 021523,Date:Feb/12/2017")
print(match.group('name'))
# 021523
print(match.group('id'))
# Feb/12/2017

# 寻找所有匹配
print(10)
print(re.findall(r"r[ua]n", "run,ran,run"))
# ['run', 'ran', 'run']

# 替换
print(re.sub(r"r[au]ns", "catches", "dog runs to cat"))

# 分裂
print(re.split(r"[,;\.\\]", "a;b.c\d;e"))
# ['a', 'b', 'c', 'd', 'e']

# compile
compiled_re = re.compile(r"r[ua]n")
print(compiled_re.search("dog ran to cat"))



# ....

小抄

小抄地址:https://static.mofanpy.com/static/results/basic/13-10-01.png