码迷,mamicode.com
首页 > 其他好文 > 详细

正则表达式

时间:2018-07-19 13:52:48      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:c99   运行   ssi   pre   16px   表达   perl   结果   字符串   

正则表达式,又称正规表示式、正规表示法、正规表达式、规则表达式、常规表示法(英语:Regular Expression,在代码中常简写为regex、regexp或RE),计算机科学的一个概念。正则表达式使用单个字符串来描述、匹配一系列匹配某个句法规则的字符串。在很多文本编辑器里,正则表达式通常被用来检索、替换那些匹配某个模式的文本。

许多程序设计语言都支持利用正则表达式进行字符串操作。例如,在Perl中就内建了一个功能强大的正则表达式引擎。正则表达式这个概念最初是由Unix中的工具软件(例如sed和grep)普及开的。正则表达式通常缩写成“regex”,单数有regexp、regex,复数有regexps、regexes、regexen。
引用自维基百科https://zh.wikipedia.org/wiki/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F

以上来自https://www.cnblogs.com/chuxiuhong/p/5885073.html

正则表达式用于匹配字符串。

re模块的match()方法是从开头匹配

技术分享图片
import re
d=re.match(abc,abcdfaff)
print(d)
#返回:<_sre.SRE_Match object; span=(0, 3), match=‘abc‘>
View Code
技术分享图片
#要想知道匹配的是什么,就在匹配的返回值变量后加.group(0)
import re
d=re.match(abc,abcdfaff)
print(d.group(0))
#返回:abc
View Code

re的findall()方法可以从任意位置处匹配:

技术分享图片
#匹配数字0到10次,1到10次的运行结果:
import re
d=re.findall([0-9]{0,10},123456ab789cdfGFFDaff)
#d=re.findall(‘[0-9]{1,10}‘,‘987868969354465766776ab6cdfaff‘)
if d:
    print(d)
#the running result:[‘123456‘, ‘‘, ‘‘, ‘789‘, ‘‘, ‘‘, ‘‘, ‘‘, ‘‘, ‘‘, ‘‘, ‘‘, ‘‘, ‘‘, ‘‘]
#the running result:[‘123456‘, ‘789‘]
View Code
技术分享图片
#匹配小写与大写字母0到10次,1到10次的运行结果:
import re
d=re.findall([a-zA-Z]{1,10},123456ab789cdfGFFDaff)
if d:
    print(d)
#the running result:[‘‘, ‘‘, ‘‘, ‘‘, ‘‘, ‘‘, ‘ab‘, ‘‘, ‘‘, ‘‘, ‘cdfGFFDaff‘, ‘‘]
#the running result:[‘ab‘, ‘cdfGFFDaff‘]
View Code
技术分享图片
#匹配一个或者多个字符串:
import re
d=re.findall([a-zA-Z]+,123_456ab7.89c~dfGFFDaff)
if d:
    print(d)
#the running result:[‘ab‘, ‘c‘, ‘dfGFFDaff‘]
View Code

re的search()方法:

技术分享图片
#匹配一个或者多个数字,从头开始找,直到找到第一个字符串为止:
import re
d=re.search(\d+,def123_456ab7.89c~dfGFFDaff)
if d:
    print(d.group())
#the running result:123
View Code

re的sub()方法,用于替换的:

技术分享图片
#把所有的数字替换成‘<‘,下面分别展示的是‘d‘和‘d+‘方法:
import re
d=re.sub(\d+,<,def123_456ab7.89c~dfGFFDaff)
if d:
    print(d)
#the running result:def<<<_<<<ab<.<<c~dfGFFDaff
#the running result:def<_<ab<.<c~dfGFFDaff
View Code

re的sub()方法,用于部分替换的:

技术分享图片
#只替换前两个数字字符串:
import re
d=re.sub(\d+,<,def123_456ab7.89c~dfGFFDaff,count=2)
if d:
    print(d)
#the running result:def<_<ab7.89c~dfGFFDaff
View Code

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

正则表达式

标签:c99   运行   ssi   pre   16px   表达   perl   结果   字符串   

原文地址:https://www.cnblogs.com/yibeimingyue/p/9334759.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!