女神图开篇(Winona Ryder)
正则表达式看了好多回了都没有记住--_--
太多了,先记住几种最常用的吧
参考 官方docs 看官方文档和源码是最高效的。信息可靠且没有信息传递衰减。没有中间商赚差价。
# re.py
# re 模块的 两个重要函数
def match(pattern, string, flags=0):
"""Try to apply the pattern at the start of the string, returning
a Match object, or None if no match was found."""
return _compile(pattern, flags).match(string)
def split(pattern, string, maxsplit=0, flags=0):
"""Split the source string by the occurrences of the pattern,
returning a list containing the resulting substrings. If
capturing parentheses are used in pattern, then the text of all
groups in the pattern are also returned as part of the resulting
list. If maxsplit is nonzero, at most maxsplit splits occur,
and the remainder of the string is returned as the final element
of the list."""
return _compile(pattern, flags).split(string, maxsplit)
挑几条实用的,从简到繁。
用\d可以匹配一个数字,\w可以匹配一个字母或数字,\s可以匹配一个空格(也包括Tab等空白符)
# 记忆 d : dicimal w : word s : spacing
.可以匹配任意字符
'''
'00\d'可以匹配'007',但无法匹配'00A';
'\d\d\d'可以匹配'010';
'\w\w\d'可以匹配'py3';
'''
# 'py.'可以匹配'pyc'、'pyo'、'py!'等等。
要匹配变长的字符,在正则表达式中,
用*表示任意个字符(包括0个),用+表示至少一个字符,用?表示0个或1个字符,
# 记忆 ? : yes or no (0 or 1) 范围 0-1
# + : 表示存在 范围 1-N
# * : 很多分叉代表所有情况 范围 0-N
用{n}表示n个字符,用{n,m}表示n到m个字符
'''
来看一个复杂的例子:\d{3}\s+\d{3,8}
我们来从左到右解读一下:
\d{3}表示匹配3个数字,例如'010';
\s可以匹配一个空格(也包括Tab等空白符),所以\s+表示至少有一个空格,例如匹配' ',' '等
\d{3,8}表示3-8个数字,例如'1234567'。
'''
# 进阶 要做更精确地匹配,可以用[]表示范围
'''
[0-9a-zA-Z\_]可以匹配一个数字、字母或者下划线;
[0-9a-zA-Z\_]+可以匹配至少由一个数字、字母或者下划线组成的字符串,比如'a100','0_Z','Py3000'等等;
[a-zA-Z\_][0-9a-zA-Z\_]*可以匹配由字母或下划线开头,后接任意个由一个数字、字母或者下划线组成的字符串,也就是Python合法的变量;
[a-zA-Z\_][0-9a-zA-Z\_]{0, 19}更精确地限制了变量的长度是1-20个字符(前面1个字符+后面最多19个字符)。
'''
# 还有一点补充
'''
A|B可以匹配A或B,所以(P|p)ython可以匹配'Python'或者'python'。
^表示行的开头,^\d表示必须以数字开头。
$表示行的结束,\d$表示必须以数字结束。
注意,py也可以匹配'python',但是加上^py$就变成了整行匹配,就只能匹配'py'了。
'''
看这三个教程应该够了
两个重要方法
-
re.match(pattern, string)`方法判断是否匹配,如果匹配成功,返回一个`Match`对象,否则返回`None # re.split(pattern, string) 方法返回满足条件的 字符子串列表,其中的pattern是分割条件 re.split(r'[\s\,]+', 'a,b, c d') ['a', 'b', 'c', 'd']
实例
1.提取字符串中的数字
import re
s = "+539.298000"
m = re.findall(r'\d+',s)
# ['539', '298000']
2.判断字符串中是否有数字
s = "+539.298000"
m = re.match(r'.*[0-9]+.*',s)
# <re.Match object; span=(0, 12), match='+-539.298000'>