python re正则总结

1. re基础

1.1 正则在不同的语言中有区别,但是大部分是通用的


re元字符和语法

1.2 贪婪和非贪婪(默认是贪婪的)
开启非贪婪模式需要在表达式后加"?"

1.3 转移字符 ""
原生字符串r"\d"解决了匹配"\d"的问题

1.4 匹配模式
re.compile(pattern[,flag])

2. re模块

2.1 用法

import re

pattern = re.compile(r"hello")
match = pattern.match("hello world.")
if match:
    print(match.group())
  • re.compile(str,flag)
    负责将字符串形式的正则表达式编译成pattern对象
    匹配模式有:
    • re.I,忽略大小写
    • re.M 多行模式
    • re.S 任意匹配模式
a = re.compile(r"""\d+  #intergal part
                   \.   #decimal part
                   \d*  #fractional digits""",re.X)
#等价于
b = re.compile(r"\d+\.\d*")
m = re.match(r"hello","hello world.")
print(m.group())

2.2 match
match对象是一次匹配的结果

import re
m = re.match(r'(\w+) (\w+)(?P<sign>.*)', 'hello world!')
 
print "m.string:", m.string
print "m.re:", m.re
print "m.pos:", m.pos
print "m.endpos:", m.endpos
print "m.lastindex:", m.lastindex
print "m.lastgroup:", m.lastgroup
 
print "m.group(1,2):", m.group(1, 2)
print "m.groups():", m.groups()
print "m.groupdict():", m.groupdict()
print "m.start(2):", m.start(2)
print "m.end(2):", m.end(2)
print "m.span(2):", m.span(2)
print r"m.expand(r'\2 \1\3'):", m.expand(r'\2 \1\3')

2.3 pattern
pattern对象是编译好的正则表达式,通过re.compile()构造实例

import re
p = re.compile(r'(\w+) (\w+)(?P<sign>.*)', re.DOTALL)
 
print "p.pattern:", p.pattern
print "p.flags:", p.flags
print "p.groups:", p.groups
print "p.groupindex:", p.groupindex

#search 
import re 
 
# 将正则表达式编译成Pattern对象 
pattern = re.compile(r'world') 
 
# 使用search()查找匹配的子串,不存在能匹配的子串时将返回None 
# 这个例子中使用match()无法成功匹配 
match = pattern.search('hello world!') 
 
if match: 
    # 使用Match获得分组信息 
    print match.group() 

#split
p = re.compile(r'\d+')
print p.split('one1two2three3four4')

#findall
p = re.compile(r'\d+')
print p.findall('one1two2three3four4')

#sub
p = re.compile(r'(\w+) (\w+)')
s = 'i say, hello world!'
 
print p.sub(r'\2 \1', s)
 
def func(m):
    return m.group(1).title() + ' ' + m.group(2).title()
 
print p.sub(func, s)
  • 字符串匹配
re.search("abc","hello abc")
re.search("gray|grey","gray")
re.search("gr(a|e)y","gray")
# 数量限定
‘+’ 加号代表前面的字符必须至少出现一次
? 问号代表前面的字符最多只可以出现一次
‘*’ 星号代表前面的字符可以不出现,也可以出现一次或者多次
 [...] 括号里面包含的任意字符
匹配 [0-9],[0-9a-z]
多字符匹配 {n}
[0-9]{3} : []以内的字母、数字在后面字符串中出现的次数
[]{m,n}, 按照[]内规则匹配 m---n之间个数,m必须小于n
"." 匹配任何1个字符
"^" 匹配字符串的开始
"$" 匹配字符串的结尾
'\d' 匹配数字
'\D' 匹配非数字
'\w' 匹配任意数字和字母
'\W' 非数字和字母
'\s' 匹配任意空白字符,相当于 [ \t\n\r\f\v]
\S 匹配任意非空白字符

match() 函数只在字符串的开始位置尝试匹配正则表达式,也就是只报告从位置 0 开始的匹配情况
search() 函数是扫描整个字符串来查找匹配
split() 将字符串按照规则分成list
findall() 函数搜索整个字符串,返回所有匹配项的list
sub() 函数 查找并替换

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容