Python Regular Expressions (Python 正则表达式)

本文来自于Google Developers中对于Python的介绍。https://developers.google.com/edu/python/regular-expressions。

这篇文章使用 Markdown 写成。

认识正则表达式

Python的正则表达式是使用 re 模块的。

match = re.search(pattern,str)
if match:print 'found',match.group()
else:print 'NOT Found!'

正则表达式的规则

基本规则

  • a, x, 9 都是普通字符 (ordinary characters)
  • . (一个点)可以匹配任何单个字符(除了'\n')
  • \w(小写的w)可以匹配一个单词里面的字母,数字或下划线 [a-zA-Z0-9_];\W (大写的W)可以匹配非单词里的这些元素
  • \b 匹配单词与非单词的分界
  • \s(小写的s)匹配一个 whitespace character,包括 space,newline,return,tab,form(\n\r\t\f);\S(大写的S)匹配一个非 whitespace character
  • \d 匹配十进制数字 [0-9]
  • ^=start,$=end 用来匹配字符串的开始和结束
  • \ 是转义字符,用 . 来匹配串里的'.',等

一些基本的例子

## 在字符串'piiig'中查找'iii'
match = re.search(r'iii', 'piiig') =>  found, match.group() == "iii"
match = re.search(r'igs', 'piiig') =>  not found, match == None## . 匹配除了\n的任意字符
match = re.search(r'..g', 'piiig') =>  found, match.group() == "iig"## \d 匹配0-9的数字字符, \w 匹配单词里的字符
match = re.search(r'\d\d\d', 'p123g') =>  found, match.group() == "123"
match = re.search(r'\w\w\w', '@@abcd!!') =>  found, match.group() == "abc"

重复

可以用'+' '*' '?'来匹配0个,1个或多个重复字符。

  • '+' 用来匹配1个或者多个字符
  • '*' 用来匹配0个或者多个字符
  • '?' 用来匹配0个或1个字符

注意,'+'和'*'会匹配尽可能多的字符。

一些重复字符的例子

## i+  匹配1个或者多个'i'
match = re.search(r'pi+', 'piiig') =>  found, match.group() == "piii"## 找到字符串中最左边尽可能长的模式。
## 注意,并没有匹配到第二个 'i+'
match = re.search(r'i+', 'piigiiii') =>  found, match.group() == "ii"## \s*  匹配0个或1个空白字符 whitespace
match = re.search(r'\d\s*\d\s*\d', 'xx1 2   3xx') =>  found, match.group() == "1 2   3"
match = re.search(r'\d\s*\d\s*\d', 'xx12  3xx') =>  found, match.group() == "12  3"
match = re.search(r'\d\s*\d\s*\d', 'xx123xx') =>  found, match.group() == "123"## ^ 匹配字符串的第一个字符
match = re.search(r'^b\w+', 'foobar') =>  not found, match == None
## 与上例对比
match = re.search(r'b\w+', 'foobar') =>  found, match.group() == "bar"

Email

考虑一个典型的Email地址:someone@host.com,可以用如下的方式匹配:

match = re.search(r'\w+@\w+',str)

但是,对于这种Email地址 'xyz alice-b@google.com purple monkey' 则不能奏效。

使用方括号

方括号里面的字符表示一个字符集合。[abc]可以被用来匹配'a'或者'b'或者'c'。\w \s等都可以用在方括号里,除了'.'以外,它只能用来表示字面意义上的‘点’。所以上面的Email规则可以扩充如下:

match = re.search('r[\w.-]+@[\w.-]+',str)

你还可以使用'-'来指定范围,如[a-z]指示的是所有小写字母的集合。所以如果你想构造的字符集合中有'-',请把它放到末尾[ab-]。另外,前方加上'^',用来表示取集合的补集,例如[^ab]表示除了'a'和'b'之外的其他字符。

操作

以Email地址为例,如果我们想要分别提取该地址的用户名'someone'和主机名'host.com'该怎么办呢?可以在模式中用圆括号指定。

  str = 'purple alice-b@google.com monkey dishwasher'match = re.search('([\w.-]+)@([\w.-]+)', str)   #用圆括号指定分割if match:print match.group()   ## 'alice-b@google.com' (the whole match)print match.group(1)  ## 'alice-b' (the username, group 1)print match.group(2)  ## 'google.com' (the host, group 2)

findall 函数

与group函数只找到最左端的一个匹配不同,findall函数找到字符串中所有与模式匹配的串。

  str = 'purple alice@google.com, blah monkey bob@abc.com blah dishwasher'## findall返回一个包含所有匹配结果的 listemails = re.findall(r'[\w\.-]+@[\w\.-]+', str) ## ['alice@google.com', 'bob@abc.com']for email in emails:print email

在文件中使用findall

当然可以读入文件的每一行,然后对每一行的内容调用findall,但是为什么让这一切自动发生呢?

f = open(filename.txt,'r')
matches = re.findall(pattern,f.read())

findall 和分组

和group的用法相似,也可以指定分组。

str = 'purple alice@google.com, blah monkey bob@abc.com blah dishwasher'
## 返回了一个list
tuples = re.findall(r'([\w\.-]+)@([\w\.-]+)', str)
print tuples  ## [('alice', 'google.com'), ('bob', 'abc.com')]
## list中的元素是tuple
for tuple in tuples:print tuple[0]  ## usernameprint tuple[1]  ## host

调试

正则表达式异常强大,使用简单的几条规则就可以演变出很多的模式组合。在确定你的模式之前,可能需要很多的调试工作。在一个小的测试集合上测试正则表达式。

其他选项

正则表达式还可以设置“选项”。

match = re.search(pat,str,opt)

这些可选项如下:

  • IGNORECASE 忽视大小写
  • DOTALL 允许'.'匹配'\n'
  • MULTILINE 在一个由许多行组成的字符串中,允许'^'和'$'匹配每一行的开始和结束

转载于:https://www.cnblogs.com/xmfbit/p/3872180.html

Python的正则表达式相关推荐

  1. Python中正则表达式用法 重点格式以这个为准_首看_各种问题

    20210811 https://www.jb51.net/article/101258.htm 一.惰性模式的概念: 此模式和贪婪模式恰好相反,它尽可能少的匹配字符以满足正则表达式即可,例如: va ...

  2. python使用正则表达式判别字符串是否以一个大写字符起始而跟随了一些小写字符

    python使用正则表达式判别字符串是否以一个大写字符起始而跟随了一些小写字符 # # Python3 code to find sequences of one upper # case lette ...

  3. python使用正则表达式统计字符串中出现次数最多的数字

    python使用正则表达式统计字符串中出现次数最多的数字 #python使用正则表达式统计字符串中出现次数最多的数字 # find the most occurring element import ...

  4. python使用正则表达式识别大写字母并在大写字母前插入空格

    python使用正则表达式识别大写字母并在大写字母前插入空格 #python使用正则表达式识别大写字母并在大写字母前插入空格 import redef putSpace(input):# regex ...

  5. python使用正则表达式删除字符串中的其它字符只保留数字和字母

    python使用正则表达式删除字符串中的其它字符只保留数字和字母 #python使用正则表达式删除字符串中的其它字符只保留数字和字母 # Python code to demonstrate # to ...

  6. python使用正则表达式寻找具有特定后缀的文件

    python使用正则表达式寻找具有特定后缀的文件 # python使用正则表达式寻找具有特定后缀的文件 # import library import re# list of different ty ...

  7. python使用正则表达式抽取字符串中最大数值数字

    python使用正则表达式抽取字符串中最大数值数字 #python使用正则表达式抽取字符串中最大数值数字 # Function to extract maximum numeric value fro ...

  8. python使用正则表达式去除句子中的重复词

    python使用正则表达式去除句子中的重复词 #python使用正则表达式去除句子中的重复词 # Python program to remove duplicate words # using Re ...

  9. python使用正则表达式检测给定的URL地址是否合法

    python使用正则表达式检测给定的URL地址是否合法 # python使用正则表达式检测给定的URL地址是否合法 # python使用正则表达式检测给定的URL地址是否合法 # Check if a ...

  10. python使用正则表达式验证邮箱地址语法有效性

    python使用正则表达式验证邮箱地址语法有效性 #python使用正则表达式验证邮箱地址语法有效性 import re # mail regular expression formula# rege ...

最新文章

  1. java.utilDate和java.sql.Date
  2. 清华教授穿红色短裤火“出圈”,网友:哈哈哈哈太真实了
  3. 期末Linux复习容易迷糊的地方!
  4. SAP MM MIGO过账报错 - 用本币计算的余额 - 之对策
  5. 手写Python中列表和字符串的反转
  6. html页面渲染vue组件,Vue组件页面渲染的基本流程
  7. SAP Spartacus not found的页面处理机制
  8. python中的items方法_Python 字典的items()方法和iteritems()方法有什么不同?【面试题详解】...
  9. MySQL——基本配置
  10. 属性加密测试用例相关问题的分析
  11. win10 查看文件扩展名 - 教程篇
  12. 利用vbs读取XML中的某个指定子叶节点 (转)
  13. Android SharedPreferences
  14. php课设报告致谢_奇安信CERT发布1月安全监测报告:需警惕这19个高危漏洞
  15. LSDB和SPF算法
  16. DXP PCB板的形状的改变
  17. 利用GSensor让屏幕实现360度旋转
  18. Ubuntu 开机自动运行命令
  19. VS2022 支持XP
  20. oracle与sql语句

热门文章

  1. MyBatis学习总结(10)——批量操作
  2. JavaScript 设计模式的七大原则(未完成)
  3. 微积分学习笔记四:空间向量基础
  4. KOA 在typescript下编译找不到模板render和session错误的解决
  5. 如何优雅的编写 JavaScript 代码
  6. Android编程 系统资源的介绍
  7. 深入浅出搜索架构引擎、方案与细节(上)
  8. linux下Redis以及phpredis扩展安装
  9. JVMTOP JVM 监视工具
  10. Oracle 10g新增DROP DATABASE命令