re-正则表达式

2020-04-14  本文已影响0人  huashen_9126

搜索匹配

re.match #只匹配字符串的开始,不常用
re.match(pattern, string, flags=0)
re.search #匹配整个字符串,常用
re.search(pattern, string, flags=0)

import re
 
line = "Cats are smarter than dogs";
 
matchObj = re.match( r'dogs', line, re.M|re.I)
if matchObj:
   print("match --> matchObj.group() : ", matchObj.group())
else:
   print("No match!!")
 
matchObj = re.search( r'dogs', line, re.M|re.I)
if matchObj:
   print("search --> searchObj.group() : ", matchObj.group())
else:
   print("No match!!")

输出:
No match!!
search --> searchObj.group() : dogs

'(?P...)' 分组匹配

import re
s = '1102231990xxxxxxxx'
res = re.search('(?P<province>\d{3})(?P<city>\d{3})(?P<born_year>\d{4})',s)
print(res.groupdict())

输出:
{'province': '110', 'city': '223', 'born_year': '1990'}

检索替换

re.sub(pattern, repl, string, count=0, flags=0)

  • pattern : 正则中的模式字符串。
  • repl : 替换的字符串,也可为一个函数。
  • string : 要被查找替换的原始字符串。
  • count : 模式匹配后替换的最大次数,默认 0 表示替换所有的匹配。
#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
import re
 
phone = "2004-959-559 # 这是一个国外电话号码"
 
# 删除字符串中的 Python注释 
num = re.sub(r'#.*$', "", phone)
print "电话号码是: ", num
 
# 删除非数字(-)的字符串 
num = re.sub(r'\D', "", phone)
print "电话号码是 : ", num

输出:
电话号码是: 2004-959-559
电话号码是 : 2004959559

repl是一个函数

import re
 
# 将匹配的数字乘以 2
def double(matched):
    value = int(matched.group('value'))
    return str(value * 2)
 
s = 'A23G4HFD567'
print(re.sub('(?P<value>\d+)', double, s))

输出:
A46G8HFD1134


继续学习

re.compilere.findallre.finditerre.split
参考:菜鸟教程

上一篇 下一篇

猜你喜欢

热点阅读