【362】python 正则表达式

参考:正则表达式 - 廖雪峰

参考:Python3 正则表达式 - 菜鸟教程

参考:正则表达式 - 教程


re.match 尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回none。

re.search 扫描整个字符串并返回第一个成功的匹配。

  • span():返回搜索的索引区间
  • group():返回匹配的结果

re.sub 用于替换字符串中的匹配项。

re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;而re.search匹配整个字符串,直到找到一个匹配。

Python 的re模块提供了re.sub用于替换字符串中的匹配项。

compile 函数用于编译正则表达式,生成一个正则表达式( Pattern )对象,供 match() 和 search() 这两个函数使用。

findall 在字符串中找到正则表达式所匹配的所有子串,并返回一个列表,如果没有找到匹配的,则返回空列表。

注意: match 和 search 是匹配一次 findall 匹配所有。

finditer 和 findall 类似,在字符串中找到正则表达式所匹配的所有子串,并把它们作为一个迭代器返回。

split 方法按照能够匹配的子串将字符串分割后返回列表 


 \d 可以匹配一个数字;

\d matches any digit, while \D matches any nondigit:

 \w 可以匹配一个字母或数字或者下划线;

\w matches any character that can be part of a word (Python identifier), that is, a letter, the underscore or a digit, while \W matches any other character:

 \W 可以匹配非数字字母下划线;

 \s 表示一个空白格(也包括Tab、回车等空白格);

\s matches any space, while \S matches any nonspace character:

 . 表示任意字符;

 * 表示任意字符长度(包括0个)(>=0);(其前面的一个字符,或者通过小括号匹配多个字符)

# 匹配最左边,即是0个字符
>>> re.search('\d*', 'a123456b')
<_sre.SRE_Match object; span=(0, 0), match=''># 匹配最长
>>> re.search('\d\d\d*', 'a123456b')
<_sre.SRE_Match object; span=(1, 7), match='123456'>>>> re.search('\d\d*', 'a123456b')
<_sre.SRE_Match object; span=(1, 7), match='123456'># 两个的倍数匹配
>>> re.search('\d(\d\d)*', 'a123456b')
<_sre.SRE_Match object; span=(1, 6), match='12345'>

  

 + 表示至少一个字符(>=1);(其前面的一个字符,或者通过小括号匹配多个字符)

>>> re.search('.\d+', 'a123456b')
<_sre.SRE_Match object; span=(0, 7), match='a123456'>>>> re.search('(.\d)+', 'a123456b')
<_sre.SRE_Match object; span=(0, 6), match='a12345'>

  

 ? 表示0个或1个字符;(其前面的一个字符,或者通过小括号匹配多个字符)

>>> re.search('\s(\d\d)?\s', 'a 12 b')
<_sre.SRE_Match object; span=(1, 5), match=' 12 '>>>> re.search('\s(\d\d)?\s', 'a  b')
<_sre.SRE_Match object; span=(1, 3), match='  '>>>> re.search('\s(\d\d)?\s', 'a 1 b')
# 无返回值,没有匹配成功

  

[] 匹配,同时需要转义的字符,在里面不需要,如 [.] 表示点

>>> re.search('[.]', 'abcabc.123456.defdef')
<re.Match object; span=(6, 7), match='.'>>>> # 一次匹配中括号里面的任意字符
>>> re.search('[cba]+', 'abcabc.123456.defdef')
<re.Match object; span=(0, 6), match='abcabc'>>>> re.search('.[\d]*', 'abcabc.123456.defdef')
<re.Match object; span=(0, 1), match='a'>>>> re.search('\.[\d]*', 'abcabc.123456.defdef')
<re.Match object; span=(6, 13), match='.123456'>>>> re.search('[.\d]+', 'abcabc.123456.defdef')
<re.Match object; span=(6, 14), match='.123456.'>

 

 {n} 表示n个字符;

 {n,m} 表示n-m个字符;

 [0-9a-zA-Z\_] 可以匹配一个数字、字母或者下划线;

 [0-9a-zA-Z\_]+ 可以匹配至少由一个数字、字母或者下划线组成的字符串,比如'a100''0_Z''Py3000'等等;

 [a-zA-Z\_][0-9a-zA-Z\_]* 可以匹配由字母或下划线开头,后接任意个由一个数字、字母或者下划线组成的字符串,也就是Python合法的变量;

 [a-zA-Z\_][0-9a-zA-Z\_]{0, 19} 更精确地限制了变量的长度是1-20个字符(前面1个字符+后面最多19个字符)。

- 在 [] 中表示范围,如果横线挨着中括号则被视为真正的横线
Ranges of letters or digits can be provided within square brackets, letting a hyphen separate the first and last characters in the range. A hyphen placed after the opening square bracket or before the closing square bracket is interpreted as a literal character:

>>> re.search('[e-h]+', 'ahgfea')
<re.Match object; span=(1, 5), match='hgfe'>>>> re.search('[B-D]+', 'ABCBDA')
<re.Match object; span=(1, 5), match='BCBD'>>>> re.search('[4-7]+', '154465571')
<re.Match object; span=(1, 8), match='5446557'>>>> re.search('[-e-gb]+', 'a--bg--fbe--z')
<re.Match object; span=(1, 12), match='--bg--fbe--'>>>> re.search('[73-5-]+', '14-34-576')
<re.Match object; span=(1, 8), match='4-34-57'>

^ 在 [] 中表示后面字符除外的其他字符

Within a square bracket, a caret after placed after the opening square bracket excludes the characters that follow within the brackets:

>>> re.search('[^4-60]+', '0172853')
<re.Match object; span=(1, 5), match='1728'>>>> re.search('[^-u-w]+', '-stv')
<re.Match object; span=(1, 3), match='st'>

 

 A|B 可以匹配A或B,所以(P|p)ython可以匹配'Python'或者'python'

Whereas square brackets surround alternative characters, a vertical bar separates alternative patterns:

>>> re.search('two|three|four', 'one three two')
<re.Match object; span=(4, 9), match='three'>>>> re.search('|two|three|four', 'one three two')
<re.Match object; span=(0, 0), match=''>>>> re.search('[1-3]+|[4-6]+', '01234567')
<re.Match object; span=(1, 4), match='123'>>>> re.search('([1-3]|[4-6])+', '01234567')
<re.Match object; span=(1, 7), match='123456'>>>> re.search('_\d+|[a-z]+_', '_abc_def_234_')
<re.Match object; span=(1, 5), match='abc_'>>>> re.search('_(\d+|[a-z]+)_', '_abc_def_234_')
<re.Match object; span=(0, 5), match='_abc_'>

 

 ^ 表示行的开头,^\d表示必须以数字开头。

 $ 表示行的结束,\d$表示必须以数字结束。

A caret at the beginning of the pattern string matches the beginning of the data string; a dollar at the end of the pattern string matches the end of the data string:

>>> re.search('\d*', 'abc')
<re.Match object; span=(0, 0), match=''>>>> re.search('^\d*', 'abc')
<re.Match object; span=(0, 0), match=''>>>> re.search('\d*$', 'abc')
<re.Match object; span=(3, 3), match=''>>>> re.search('^\d*$', 'abc')>>> re.search('^\s*\d*\s*$', ' 345 ')
<re.Match object; span=(0, 5), match=' 345 '>

如果不在最前或最后,可以视为普通字符,但是在最前最后的时候想变成普通字符需要加上反斜杠

Escaping a dollar at the end of the pattern string, escaping a caret at the beginning of the pattern string or after the opening square bracket of a character class, makes dollar and caret lose the special meaning they have in those contexts context and let them be treated as literal characters:

>>> re.search('\$', '$*')
<re.Match object; span=(0, 1), match='$'>>>> re.search('\^', '*^')
<re.Match object; span=(1, 2), match='^'>>>> re.search('[\^]', '^*')
<re.Match object; span=(0, 1), match='^'>>>> re.search('[^^]', '^*')
<re.Match object; span=(1, 2), match='*'>

 

 ^(\d{3})-(\d{3,8})$ 分别定义了两个组,可以直接从匹配的字符串中提取出区号和本地号码:

  • group(0):永远是原始字符串;
  • group(1):表示第1个子串;
  • group(2):表示第2个子串,以此类推。

分组顺序:按照左括号的顺序开始

Parentheses allow matched parts to be saved. The object returned by re.search() has a group() method that without argument, returns the whole match and with arguments, returns partial matches; it also has a groups()method that returns all partial matches:

>>> R = re.search('((\d+) ((\d+) \d+)) (\d+ (\d+))','  1 23 456 78 9 0 ')>>> R
<re.Match object; span=(2, 15), match='1 23 456 78 9'>>>> R.group()
'1 23 456 78 9'>>> R.groups()
('1 23 456', '1', '23 456', '23', '78 9', '9')>>> [R.group(i) for i in range(len(R.groups()) + 1)]
['1 23 456 78 9', '1 23 456', '1', '23 456', '23', '78 9', '9']

?: 二选一,括号不计入分组

>>> R = re.search('([+-]?(?:0|[1-9]\d*)).*([+-]?(?:0|[1-9]\d*))',' a = -3014, b = 0 ')>>> R
<re.Match object; span=(5, 17), match='-3014, b = 0'>>>> R.groups()
('-3014', '0')

 

 

 .* 表示任意匹配除换行符(\n、\r)之外的任何单个或多个字符

模式描述
^匹配字符串的开头
$匹配字符串的末尾。
.匹配任意字符,除了换行符,当re.DOTALL标记被指定时,则可以匹配包括换行符的任意字符。
[...]用来表示一组字符,单独列出:[amk] 匹配 'a','m'或'k'
[^...]不在[]中的字符:[^abc] 匹配除了a,b,c之外的字符。
re*匹配0个或多个的表达式。
re+匹配1个或多个的表达式。
re?匹配0个或1个由前面的正则表达式定义的片段,非贪婪方式
re{ n}匹配n个前面表达式。例如,"o{2}"不能匹配"Bob"中的"o",但是能匹配"food"中的两个o。
re{ n,}精确匹配n个前面表达式。例如,"o{2,}"不能匹配"Bob"中的"o",但能匹配"foooood"中的所有o。"o{1,}"等价于"o+"。"o{0,}"则等价于"o*"。
re{ n, m}匹配 n 到 m 次由前面的正则表达式定义的片段,贪婪方式
a| b匹配a或b
(re)匹配括号内的表达式,也表示一个组
(?imx)正则表达式包含三种可选标志:i, m, 或 x 。只影响括号中的区域。
(?-imx)正则表达式关闭 i, m, 或 x 可选标志。只影响括号中的区域。
(?: re)类似 (...), 但是不表示一个组
(?imx: re)在括号中使用i, m, 或 x 可选标志
(?-imx: re)在括号中不使用i, m, 或 x 可选标志
(?#...)注释.
(?= re)前向肯定界定符。如果所含正则表达式,以 ... 表示,在当前位置成功匹配时成功,否则失败。但一旦所含表达式已经尝试,匹配引擎根本没有提高;模式的剩余部分还要尝试界定符的右边。
(?! re)前向否定界定符。与肯定界定符相反;当所含表达式不能在字符串当前位置匹配时成功。
(?> re)匹配的独立模式,省去回溯。
\w匹配数字字母下划线
\W匹配非数字字母下划线
\s匹配任意空白字符,等价于 [\t\n\r\f]。
\S匹配任意非空字符
\d匹配任意数字,等价于 [0-9]。
\D匹配任意非数字
\A匹配字符串开始
\Z匹配字符串结束,如果是存在换行,只匹配到换行前的结束字符串。
\z匹配字符串结束
\G匹配最后匹配完成的位置。
\b匹配一个单词边界,也就是指单词和空格间的位置。例如, 'er\b' 可以匹配"never" 中的 'er',但不能匹配 "verb" 中的 'er'。
\B匹配非单词边界。'er\B' 能匹配 "verb" 中的 'er',但不能匹配 "never" 中的 'er'。
\n, \t, 等。匹配一个换行符。匹配一个制表符, 等
\1...\9匹配第n个分组的内容。
\10匹配第n个分组的内容,如果它经匹配。否则指的是八进制字符码的表达式。

举例:

 \d{3} :匹配3个数字

 \s+ :至少有一个空格

 \d{3,8} :3-8个数字

>>> mySent = 'This book is the best book on Python or M.L. I have ever laid eyes upon.'>>> mySent.split(' ')
['This', 'book', 'is', 'the', 'best', 'book', 'on', 'Python', 'or', 'M.L.', 'I', 'have', 'ever', 'laid', 'eyes', 'upon.']>>> import re>>> listOfTokens = re.split(r'\W*', mySent)>>> listOfTokens
['This', 'book', 'is', 'the', 'best', 'book', 'on', 'Python', 'or', 'M', 'L', 'I', 'have', 'ever', 'laid', 'eyes', 'upon', '']>>> [tok for tok in listOfTokens if len(tok) > 0]
['This', 'book', 'is', 'the', 'best', 'book', 'on', 'Python', 'or', 'M', 'L', 'I', 'have', 'ever', 'laid', 'eyes', 'upon']>>> [tok.lower() for tok in listOfTokens if len(tok) > 0]
['this', 'book', 'is', 'the', 'best', 'book', 'on', 'python', 'or', 'm', 'l', 'i', 'have', 'ever', 'laid', 'eyes', 'upon']>>> [tok.lower() for tok in listOfTokens if len(tok) > 2]
['this', 'book', 'the', 'best', 'book', 'python', 'have', 'ever', 'laid', 'eyes', 'upon']
>>> 

参考:python爬虫(5)--正则表达式 - 小学森也要学编程 - 博客园  

实现删除引号内部的内容,注意任意匹配使用【.*】

a = 'Sir Nina said: \"I am a Knight,\" but I am not sure'
b = "Sir Nina said: \"I am a Knight,\" but I am not sure"
print(re.sub(r'"(.*)"', '', a),
re.sub(r'"(.*)"', '', b), sep='\n')Output:
Sir Nina said:  but I am not sure
Sir Nina said:  but I am not sure

Example from Eric Martin's learning materials of COMP9021

The following function checks that its argument is a string:

  1. that from the beginning: ^
  2. consists of possibly some spaces: ␣*
  3. followed by an opening parenthesis: \(
  4. possibly followed by spaces: ␣*
  5. possibly followed by either + or -: [+-]?
  6. followed by either 0, or a nonzero digit followed by any sequence of digits: 0|[1-9]\d*
  7. possibly followed by spaces: ␣*
  8. followed by a comma: ,
  9. followed by characters matching the pattern described by 1-7
  10. followed by a closing parenthesis: \)
  11. possibly followed by some spaces: ␣*
  12. all the way to the end: $

Pairs of parentheses surround both numbers to match to capture them. For point 5, a surrounding pair of parentheses is needed; ?: makes it non-capturing:

>>> def validate_and_extract_payoffs(provided_input):pattern = '^ *\( *([+-]?(?:0|[1-9]\d*)) *,'\' *([+-]?(?:0|[1-9]\d*)) *\) *$'match = re.search(pattern, provided_input)if match:return (match.groups())>>> validate_and_extract_payoffs('(+0, -7 )')
('+0', '-7')>>> validate_and_extract_payoffs('  (-3014,0)  ')
('-3014', '0')

 

转载于:https://www.cnblogs.com/alex-bn-lee/p/10325559.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/388394.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

在Python中使用Twitter Rest API批量搜索和下载推文

数据挖掘 &#xff0c; 编程 (Data Mining, Programming) Getting Twitter data获取Twitter数据 Let’s use the Tweepy package in python instead of handling the Twitter API directly. The two things we will do with the package are, authorize ourselves to use the …

第一套数字电子计算机,计算机试题第一套

《计算机试题第一套》由会员分享&#xff0c;可在线阅读&#xff0c;更多相关《计算机试题第一套(5页珍藏版)》请在人人文库网上搜索。1、计算机试题第一套1、计算机之所以能自动运算,就是由于采用了工作原理。A、布尔逻辑。B 储存程序。C、数字电路。D,集成电路答案选B2、“长…

Windows7 + Nginx + Memcached + Tomcat 集群 session 共享

一&#xff0c;环境说明 操作系统是Windows7家庭版&#xff08;有点不专业哦&#xff0c;呵呵&#xff01;&#xff09;&#xff0c;JDK是1.6的版本&#xff0c; Tomcat是apache-tomcat-6.0.35-windows-x86&#xff0c;下载链接&#xff1a;http://tomcat.apache.org/ Nginx…

git 版本控制(一)

新建代码库repository 1、在当前目录新建一个git代码库 git init git init projectname 2、下载一个项目&#xff0c;如果已经有了远端的代码&#xff0c;则可以使用clone下载 git clone url 增加/删除/改名文件 1、添加指定文件到暂存区 git add filename 2、添加指定目录到暂…

rollup学习小记

周末在家重构网关的Npm包&#xff0c;用到了rollup&#xff0c;记下笔记 rollup适合库library的开发&#xff0c;而webpack适合应用程序的开发。 rollup也支持tree-shaking&#xff0c;自带的功能。 package.json 也具有 module 字段&#xff0c;像 Rollup 和 webpack 2 这样的…

大数据 vr csdn_VR中的数据可视化如何革命化科学

大数据 vr csdnAstronomy has become a big data discipline, and the ever growing databases in modern astronomy pose many new challenges for analysts. Scientists are more frequently turning to artificial intelligence and machine learning algorithms to analyze…

object-c 日志

printf和NSlog区别 NSLog会自动加上换行符&#xff0c;不需要自己添加换行符&#xff0c;NSLog会加上时间和进程信息&#xff0c;而printf仅将输入的内容输出不会添加任何额外的东西。两者的输入类型也是有区别的NSLog期待NSString*&#xff0c;而printf期待const char *。最本…

计算机真正管理的文件名是什么,计算机题,请大家多多帮忙,谢谢

4、在资源管理器中&#xff0c;若想显示文件名、文件大小和文件类型&#xff0c;应采用什么显示方式。( )A、小图标显示 B、列表显示 C、详细资料显示 D、缩略图显示5、在EXCEL中&#xff0c;可以依据不同要求来提取和汇总数据&#xff0c;4、在资源管理器中&#xff0c;若想显…

小a的排列

链接&#xff1a;https://ac.nowcoder.com/acm/contest/317/G来源&#xff1a;牛客网小a有一个长度为nn的排列。定义一段区间是"萌"的&#xff0c;当且仅当把区间中各个数排序后相邻元素的差为11 现在他想知道包含数x,yx,y的长度最小的"萌"区间的左右端点 …

Xcode做简易计算器

1.创建一个新项目&#xff0c;选择“View-based Application”。输入名字“Cal”&#xff0c;这时会有如下界面。 2.选择Resources->CalViewController.xib并双击&#xff0c;便打开了资源编辑对话框。 3.我们会看到几个窗口。其中有一个上面写着Library&#xff0c;这里…

计算机 编程 教程 pdf,计算机专业教程-第3章编程接口介绍.pdf

下载第3章 编程接口介绍• DB2 UDB应用程序概述• 嵌入S Q L编程• CLI/ODBC应用程序• JAVA应用程序• DAO 、R D O 、A D O应用程序本章将介绍对DB2 UDB 可用的编程方法及其特色&#xff0c;其中一些方法附有简单的例子&#xff0c;在这些例子中&#xff0c;有些并不是只适用…

导入数据库怎么导入_导入必要的库

导入数据库怎么导入重点 (Top highlight)With the increasing popularity of machine learning, many traders are looking for ways in which they can “teach” a computer to trade for them. This process is called algorithmic trading (sometimes called algo-trading)…

windows查看系统版本号

windows查看系统版本号 winR,输入cmd&#xff0c;确定&#xff0c;打开命令窗口&#xff0c;输入msinfo32&#xff0c;注意要在英文状态下输入&#xff0c;回车。然后在弹出的窗口中就可以看到系统的具体版本号了。 winR,输入cmd&#xff0c;确定&#xff0c;打开命令窗口&…

02:Kubernetes集群部署——平台环境规划

1、官方提供的三种部署方式&#xff1a; minikube&#xff1a; Minikube是一个工具&#xff0c;可以在本地快速运行一个单点的Kubernetes&#xff0c;仅用于尝试Kubernetes或日常开发的用户使用。部署地址&#xff1a;https://kubernetes.io/docs/setup/minikube/kubeadm Kubea…

更便捷的画决策分支图的工具_做出更好决策的3个要素

更便捷的画决策分支图的工具Have you ever wondered:您是否曾经想过&#xff1a; How did Google dominate 92.1% of the search engine market share? Google如何占领搜索引擎92.1&#xff05;的市场份额&#xff1f; How did Facebook achieve 74.1% of social media marke…

供来宾访问计算机打开安全吗,计算机安全设置操作手册(22页)-原创力文档

计算机安全设置操作手册ISO27001项目实施电脑配置(以XP为例)账户设置user每台电脑设置administrator和user帐户&#xff1b;管理员账户密码至少 8位, 账户至少6位user将Administrator和user账户以外的其他账户禁用用具体步骤如下&#xff1a;、右击【我的电脑】选择【管理】如图…

Windows半透明窗口开发技巧

Windows半透明窗口开发技巧 www.visual-gear.com 原创技术文章 在windows平台上从窗口绘图有两种方法&#xff1a; 第一种响应窗口的WM_PAINT消息&#xff0c;使用窗口DC进行绘制 第二种是将窗口样式设置为层窗口&#xff0c;即 WS_EX_LAYERED设置为该样式之后窗口将不会产生任…

标识为普通SQL语法

在SQL语句的最前面增加 /*dialect*/转载于:https://www.cnblogs.com/zouhuaxin/p/10333209.html

的界面跳转

在界面的跳转有两种方法&#xff0c;一种方法是先删除原来的界面&#xff0c;然后在插入新的界面&#xff1a;如下代码 if (self.rootViewController.view.superview nil) { [singleDollController.view removeFromSuperview]; [self.view insertSubview:rootViewControlle…

计算性能提升100倍,Uber推出机器学习可视化调试工具

为了让模型迭代过程更加可操作&#xff0c;并能够提供更多的信息&#xff0c;Uber 开发了一个用于机器学习性能诊断和模型调试的可视化工具——Manifold。机器学习在 Uber 平台上得到了广泛的应用&#xff0c;以支持智能决策制定和特征预测&#xff08;如 ETA 预测 及 欺诈检测…