正则表达式

就其本质而言,正则表达式是一种小型的/高度专业化的编程语言,它内嵌在python中,并通过RE模块实现,正则表达式模式被编译成一系列的字节码,然后由用C编写的匹配引擎执行。

1.元字符

-普通字符,大多数字符和字母都会和自身匹配

-元字符

例如: .   ^   $   *   ?   { }   [  ]   |   ( )  \

>>> re.findall("a...d","abcfdasf")
['abcfd']
>>> re.findall("^a...d","abcfdasf")       # 需要找的内容必须在字符串开头
['abcfd']
>>> re.findall("x.....u$","xiaohongxiaogangxiaomingxiaowangxiaoliu")        # 需要找的内容必须在结尾
['xiaoliu']
>>> re.findall("xiaoliux+","xiaohongxiaogangxiaomingxiaowangxiaoliu")  # + (1,无穷)
[]
>>> re.findall("xiaoliux*","xiaohongxiaogangxiaomingxiaowangxiaoliu") # * (0,无穷)
['xiaoliu']
>>>
>>> re.findall("liu?","xiaohongxiaogangxiaomingxiaowangxiaoliuuu")    # ? (0,1)
['liu']
>>> re.findall("liu{3}","xiaohongxiaogangxiaomingxiaowangxiaoliuuu")       # { } 可以是任意范围
['liuuu']
>>> re.findall("liu{4}","xiaohongxiaogangxiaomingxiaowangxiaoliuuu")
[]

>>> re.findall ("q[a-z]","sdafqaa")    # q与取到的a到z相匹配
['qa']

>>> re.findall ("q[0-9]*","sdafq77aa456")  # 取数字
['q77']
>>> re.findall ("q[^a-z]","sdafq77aa456")    #  ^ 匹配 非 a-z的值
['q7']
>>> re.findall ("\([^()]*\)","12+(34*6+2-5*(2-1))")  # \ ( 将括号转换为普通括号
['(2-1)']

-------

\d 匹配任何十进制数,它相当于类[0-9]

\D 匹配任何非数字字符串,它相当于类[^0-9]

\s匹配任何空白字符,它相当于类[\t \n \r \f \v]

\S 匹配任何非空白字符,它相当于类[^ \t \n \r \f \v]

\w 匹配任何字母数字字符,它相当于类[a-zA-Z0-9]

\W 匹配任何非字母数字字符,它相当于类[^ a-zA-Z0-9]

\b 匹配一个特殊字符边界,比如空格,& ,#等

>>> re.findall ("\d+","12+(34*6+2-5*(2-1))")
['', '', '', '', '', '', '']
>>> re.findall ("\D+","12+(34*6+2-5*(2-1))")
['+(', '*', '+', '-', '*(', '-', '))']
>>> re.findall ("\s","hello world")
[' ']
>>> re.findall ("\S","hello world")
['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']
>>> re.findall ("\w+","hello world")
['hello', 'world']
>>> re.findall ("\W","hello world")
[' ']
>>> re.findall ("\w","hello1 world2")
['h', 'e', 'l', 'l', 'o', '', 'w', 'o', 'r', 'l', 'd', '']
>>> re.findall ("\w+","hello1 world2")
['hello1', 'world2']

最新文章

  1. 基于EasyUI Treegrid的权限管理资源列表
  2. 图解集合6:LinkedHashMap
  3. 最长公共子序列(加强版) Hdu 1503 Advanced Fruits
  4. 转载:Cellebrite发布新版手机取证软件,增强调查能力
  5. CoreLoation
  6. 使用 margin 让div块内容居中
  7. Mac中安装maven3.2.1
  8. Java Servlet 回顾
  9. ios swift(1)冒泡排序
  10. 为什么ajax 必须同源,same origin policy
  11. Jquery基础知识01
  12. FPGA学习笔记(三)—— 数字逻辑设计基础(抽象的艺术)
  13. maven创建web报错Cannot read lifecycle mapping metadata for artifact org.apache.maven.plugins:maven-compiler-plugin:maven-compiler-plugin:3.5.1:runtime Cause: error in opening zip file
  14. pyQt5不让进度条卡住
  15. javascript任务队列
  16. C# 对文本文件的几种读写方法总结
  17. Hadoop启动脚本分析
  18. 机器学习--k-means聚类原理
  19. c/c++二叉树的创建与遍历(非递归遍历左右中,破坏树结构)
  20. centos 7下独立的python 2.7环境安装

热门文章

  1. Vue.js中 watch的理解以及深度监听
  2. 【Python 代码】CS231n中Softmax线性分类器、非线性分类器对比举例(含python绘图显示结果)
  3. Gated CNN 阅读笔记
  4. 两个Double类型相减出现精度丢失问题
  5. java调用jni oci接口宕机原因排查
  6. shell脚本 获取第几行 第几列 的命令 awk sed
  7. hadoop 参数调优重点参数
  8. Java对象为啥要实现Serializable接口
  9. Android 调用.Net WCF服务 .
  10. Flutter 中的常见的按钮组件 以及自定义按钮组件