前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python: 正则表达式实例透析

Python: 正则表达式实例透析

作者头像
用户2183996
修改2019-09-22 17:42:36
4430
修改2019-09-22 17:42:36
举报
文章被收录于专栏:技术沉淀技术沉淀

开公众号啦,分享读书心得,欢迎一起交流成长。

re模块

代码语言:javascript
复制
import re

re.search

经常用match = re.search(pat, str)的形式。因为有可能匹配不到,所以re.search()后面一般用if statement

代码语言:javascript
复制
str = 'an example word:cat!!'
match = re.search(r'word:\w\w\w', str)
if match:
    print 'found', match.group() ## 'found word:cat'
else:
    print 'did not find'
代码语言:javascript
复制
found word:cat
代码语言:javascript
复制
# re.search return a match object, which contains lots of info
print type(match)
代码语言:javascript
复制
<type '_sre.SRE_Match'>
代码语言:javascript
复制
print match.string # source string
print match.group()
print match.start() # position of w
print match.end() # position of t
print match.endpos # position of last !
print match.span()
代码语言:javascript
复制
an example word:cat!!
word:cat
11
19
21
(11, 19)

re.match

re.matchre.search很相似,只是re.match是从字符串的开头开始匹配。

代码语言:javascript
复制
s = 'python tuts'
match = re.match(r'py',s)
if match:
    print(match.group())
代码语言:javascript
复制
py
代码语言:javascript
复制
s = 'python tuts'
match = re.search(r'^py',s)
if match:
    print(match.group())
代码语言:javascript
复制
py

常用正则字符意义

  • a, X, 9,等字符匹配自己, 元字符不匹配自己,因为有特殊意义,比如** . ^ $ * + ? { }[ ] \ | ( )**
  • . 英文句号,匹配任意字符,不包含'\n'
  • \w 匹配'word'字符,[a-zA-Z0-9]
  • \W 匹配非'word'字符
  • \b 匹配'word'和'non-word'之间边界
  • \s 匹配单个whitespace字符,space, newline, return, tab, form [\n\r\t\f]
  • \S 匹配non-whitespace字符
  • \t, \n, \r 匹配tab, newline, return
  • \d 匹配数字[0-9]
  • ^ 匹配字符串开头
  • $ 匹配字符串结尾

重复

‘+’ 一或多次, ‘*’ 零或多次, ‘?’ 零或一次

方括号[]

代码语言:javascript
复制
# 提取email address
string = 'purple alice-b@gmail.com monkey dishwasher'
match = re.search(r'\w+@\w+', string)
if match:
    print match.group()  ## 'b@google'
代码语言:javascript
复制
b@gmail

[]类似于or Square brackets can be used to indicate a set of chars, so [abc] matches 'a' or 'b' or 'c'.

代码语言:javascript
复制
match = re.search(r'[\w.-]+@[\w.-]+',string)
if match:
    print match.group()
代码语言:javascript
复制
alice-b@gmail.com

Group Extraction圆括号()

有时候需要提取匹配字符的一部分,比如刚才的邮箱,我们可能需要其中的usernamehostname,这时候可以用()分别把usernamehostname包起来,就像r'([\w.-]+)@([\w.-]+)',如果匹配成功,那么pattern不改变,只是可以用match.group(1)match.group(2)usernamehostnamematch.group()结果不变。

代码语言:javascript
复制
string = 'purple alice-b@google.com monkey dishwasher'
match = re.search(r'([\w\.-]+)@([\w\.-]+)',string)
if match:
    # Return subgroup(s) of the match by indices or names.
    print match.group() # or match.group(0)
    print match.group(1)
    print match.group(2)
if match:
    # Return a tuple containing all the subgroups of the match, from 1.
    print match.groups()
代码语言:javascript
复制
alice-b@google.com
alice-b
google.com
('alice-b', 'google.com')

findall and groups

()findall()结合,如果包括一或多个group,就返回a list of tuples

代码语言:javascript
复制
str = 'purple alice@google.com, blah monkey bob@abc.com blah dishwasher'
tuples = re.findall(r'([\w\.-]+)@([\w\.-]+)', str)
print tuples  # [('alice', 'google.com'), ('bob', 'abc.com')]
for tuple in tuples:
    print tuple[0] # username
    print tuple[1] # host
代码语言:javascript
复制
[('alice', 'google.com'), ('bob', 'abc.com')]
alice
google.com
bob
abc.com

re.search^之后是一样的。

re.sub

re.sub(pat, replacement, str)在str里寻找和pattern匹配的字符串,然后用replacement替换。replacement可以包含\1或者\2来代替相应的group,然后实现局部替换。

代码语言:javascript
复制
# replace hostname
str = 'alice@google.com, and bob@abc.com'
#returns new string with all replacements,
# \1 is group(1), \2 group(2) in the replacement
print re.sub(r'([\w\.-]+)@([\w\.-]+)', r'\1@yo-yo-dyne.com', str)
代码语言:javascript
复制
alice@yo-yo-dyne.com, and bob@yo-yo-dyne.com

参考

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016.07.15 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • re模块
  • re.search
  • re.match
  • 常用正则字符意义
  • 重复
  • 方括号[]
  • Group Extraction圆括号()
  • findall and groups
  • re.sub
  • 参考
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档