python学习-53 正则表达式
2024-08-24 12:52:37
正则表达式
就其本质而言,正则表达式是一种小型的/高度专业化的编程语言,它内嵌在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']
最新文章
- 基于EasyUI Treegrid的权限管理资源列表
- 图解集合6:LinkedHashMap
- 最长公共子序列(加强版) Hdu 1503 Advanced Fruits
- 转载:Cellebrite发布新版手机取证软件,增强调查能力
- CoreLoation
- 使用 margin 让div块内容居中
- Mac中安装maven3.2.1
- Java Servlet 回顾
- ios swift(1)冒泡排序
- 为什么ajax 必须同源,same origin policy
- Jquery基础知识01
- FPGA学习笔记(三)—— 数字逻辑设计基础(抽象的艺术)
- 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
- pyQt5不让进度条卡住
- javascript任务队列
- C# 对文本文件的几种读写方法总结
- Hadoop启动脚本分析
- 机器学习--k-means聚类原理
- c/c++二叉树的创建与遍历(非递归遍历左右中,破坏树结构)
- centos 7下独立的python 2.7环境安装