python-re模块和subprocess模块

简介: 一、re模块 re中文为正则表达式,是字符串处理的常用工具,通常用来检索和替换符合某个模式的文本。 注:要搜索的模式和字符串都可以是unicode字符串(str)和8位字符串(bytes),但是不能将unicode字符串与字节模式匹配。

一、re模块

re中文为正则表达式,是字符串处理的常用工具,通常用来检索和替换符合某个模式的文本。

注:要搜索的模式和字符串都可以是unicode字符串(str)和8位字符串(bytes),但是不能将unicode字符串与字节模式匹配。

用途:1.数据验证:测试输入的字符串是否符合规定的模式

   2.替换文本:识别文档中的特定文本,删除或替代

   3.提取字符串

常用匹配模式:

贪婪模式与非贪婪模式:

贪婪模式:总是匹配尽可能多的字符

非贪婪模式:匹配尽可能少的字符

使用findall的方式演示:

# 小写w 匹配【a-zA-Z0-9_】 大写W 匹配非字母数字下划线 【^a-zA-Z0-0】
print(re.findall('\w','hello eg-on 1_23')) #['h', 'e', 'l', 'l', 'o', 'e', 'g', 'o', 'n', '1', '2', '3']
print(re.findall('\W','hello egon 123')) #[' ', ' ']

#小写\s 匹配任意空白字符【\t\r\n\f】 大写\S 匹配任意非空字符
print(re.findall('\s','hello eg-on 1_23')) #[' ', ' ', ' ', ' ']
print(re.findall('\s','hello \n eg-on \t 1_23')) #[' ', '\n', ' ', ' ', '\t', ' ']
print(re.findall('\S','hello eg-on 1_23')) #['h', 'e', 'l', 'l', 'o', 'e', 'g', 'o', 'n', '1', '2', '3']

#\n与\t 匹配一个换行符和一个制表符
print(re.findall(r'\n','hello egon \n123')) #['\n']
print(re.findall(r'\t','hello egon\t123')) #['\n']

#\d匹配任意数字【0-9】 \D匹配任意非数字
print(re.findall('\d','hello \n e_g-on 123')) #['1', '2', '3']
print(re.findall('\D','hello \n e_g-on 123')) #['h', 'e', 'l', 'l', 'o', ' ', 'e', 'g', 'o', 'n', ' ']

# \A==>^ \Z==>$
print(re.findall('\Ahe','hello egon 123')) #['he'],\A==>^
print(re.findall('123\Z','hello egon 123')) #['he'],\Z==>$

#^ 开头 $结尾
print(re.findall('^h','hello egon 123')) #['h']
print(re.findall('3$','hello egon 123')) #['3']

# .匹配除\n外的任意字符
print(re.findall('a.b','a1b')) #['a1b']
print(re.findall('a.b','a1b a*b a b aaab')) #['a1b', 'a*b', 'a b', 'aab']
print(re.findall('a.b','a\nb')) #[]
print(re.findall('a.b','a\nb',re.S)) #['a\nb']
print(re.findall('a.b','a\nb',re.DOTALL)) #['a\nb']同上一条意思一样

#* 匹配前一个字符>=0次
print(re.findall('ab*','bbbbbbb')) #[]
print(re.findall('ab*','a')) #['a']
print(re.findall('ab*','abbbb')) #['abbbb']

#+匹配前一个字符>=1次
print(re.findall('ab+','a')) #[]
print(re.findall('ab+','abbb')) #['abbb']

#? 匹配一个字符0或者一次
print(re.findall('ab?','a')) #['a']
print(re.findall('ab?','abbb')) #['ab']

#匹配所有包含小数在内的数字
print(re.findall('\d+\.?\d*',"asdfasdf123as1.13dfa12adsf1asdf3")) #['123', '1.13', '12', '1', '3']

#.*默认为贪婪匹配
print(re.findall('a.*b','a1b22222222b')) #['a1b22222222b']

#.*?为非贪婪匹配:推荐使用
print(re.findall('a.*?b','a1b22222222b')) #['a1b']

#{n,m}
print(re.findall('ab{2}','abbb')) #['abb']
print(re.findall('ab{2,4}','abbb')) #['abb']
print(re.findall('ab{1,}','abbb')) #'ab{1,}' ===> 'ab+'
print(re.findall('ab{0,}','abbb')) #'ab{0,}' ===> 'ab*'

#[]
print(re.findall('a[1*-]b','a1b a*b a-b'))#['a1b', 'a*b', 'a-b']
print(re.findall('a[^1*-]b','a1b a*b a-b a=b')) #[]内的^代表的意思是取反,所以结果为['a=b']
print(re.findall('a[0-9]b','a1b a*b a-b a=b'))
print(re.findall('a[a-z]b','a1b a*b a-b a=b aeb'))
print(re.findall('a[a-zA-Z]b','a1b a*b a-b a=b aeb aEb'))

#():分组
print(re.findall('ab*','abababsaa123')) #['ab', 'ab', 'ab']
print(re.findall('(ab)+123','ababab123')) #['ab'],匹配到末尾的ab123中的ab
print(re.findall('(?:ab)+123','ababab123')) #findall的结果不是匹配的全部内容,而是组内的内容,?:可以让结果为匹配的全部内容
print(re.findall('href="(.*?)"','<a href="http://www.baidu.com">点击</a>'))#['http://www.baidu.com']
print(re.findall('href="(?:.*?)"','<a href="http://www.baidu.com">点击</a>'))#['href="http://www.baidu.com"']

re常用方法:

import re
#1
print(re.findall('e','alex make love') )   #['e', 'e', 'e'],返回所有满足匹配条件的结果,放在列表里
#2
print(re.search('e','alex make love').group()) #e,只到找到第一个匹配然后返回一个包含匹配信息的对象,该对象可以通过调用group()方法得到匹配的字符串,如果字符串没有匹配,则返回None。

#3
print(re.match('e','alex make love'))    #None,同search,不过在字符串开始处进行匹配,完全可以用search+^代替match

#4
print(re.split('[ab]','abcd'))     #['', '', 'cd'],先按'a'分割得到''和'bcd',再对''和'bcd'分别按'b'分割

#5
print('===>',re.sub('a','A','alex make love')) #===> Alex mAke love,不指定n,默认替换所有
print('===>',re.sub('a','A','alex make love',1)) #===> Alex make love
print('===>',re.sub('a','A','alex make love',2)) #===> Alex mAke love
print('===>',re.sub('^(\w+)(.*?\s)(\w+)(.*?\s)(\w+)(.*?)$',r'\5\2\3\4\1','alex make love')) #===> love make alex

print('===>',re.subn('a','A','alex make love')) #===> ('Alex mAke love', 2),结果带有总共替换的个数


#6
obj=re.compile('\d{2}')

print(obj.search('abc123eeee').group()) #12
print(obj.findall('abc123eeee')) #['12'],重用了obj

同样的表达式,search和findall的结果不同:

print(re.search('\(([\+\-\*\/]*\d+\.?\d*)+\)',"1-12*(60+(-40.35/5)-(-4*3))").group()) #(-40.35/5)
print(re.findall('\(([\+\-\*\/]*\d+\.?\d*)+\)',"1-12*(60+(-40.35/5)-(-4*3))")) #['/5', '*3']

#看这个例子:(\d)+相当于(\d)(\d)(\d)(\d)...,是一系列分组
print(re.search('(\d)+','123').group()) #group的作用是将所有组拼接到一起显示出来
print(re.findall('(\d)+','123')) #findall结果是组内的结果,且是最后一个组的结果

search与findall
View Code

补充:

在 python 的字符串中,\ 是被当做转义字符的。在正则表达式中,\ 也是被当做转义字符。这就导致了一个问题:如果你要匹配 \ 字符串,那么传递给 re.compile() 的字符串必须是"\\\\"。

由于字符串的转义,所以实际传递给 re.compile() 的是"\\",然后再通过正则表达式的转义,"\\" 会匹配到字符"\"。这样虽然可以正确匹配到字符 \,但是很麻烦,而且容易漏写反斜杠而导致 Bug。

原始字符串很好的解决了这个问题,通过在字符串前面添加一个r,表示原始字符串,不让字符串的反斜杠发生转义。那么就可以使用r"\\"来匹配字符\了。

二、subprocess模块

用于执行系统命令

常用方法:

  run:返回一个表示执行结果的对象

  call:返回的执行的状态码

总结:subprocess的好处是可以获取指令的执行结果

   subprocess执行指令时,可以在子进程中  这样避免造成主进程卡死

补习内容:

import re
# 1)普通的字符
# res = re.match(r'a', 'abc')
# print(res.group())

# 2)单个(非换行\n)任意字符 .
# res = re.match(r'.', 'abc')
# print(res.group())

# 3)字符集(单个) [...] eg: [abc] [a-z] [a-zA-Z0-9_]
# res = re.match(r'[a-zA-Z0-9_]', 'babc') #a-z或A-Z或0-9或_ == \w
# print(res.group())

# 4)非\w的所有字符\W  拓展:\d \D \s \S
# res = re.match(r'\W', '$babc')
# print(res.group())

# 5)开头、结尾(只适用于单行匹配) ^ $
ts = """abc
123
a1d
"""
res = re.match(r'^a', ts)
print(res)
# match 不与 $结合使用:匹配整个字符串的开头,只匹配一次
# search 可以与 $结合使用:匹配整个字符串(不限定从头开始),只匹配一次
# res = re.search(r'd$', ts)
# print(res)

# res = re.match(r'^a[\w]c$', "a_c")
# print(res)

# 6) 次数
# *[0, +œ) 尽可能多的匹配
# *? 尽可能少的匹配
# +[1, +œ) | ?[0, 1] | +? | ??
res = re.match(r'ab*?', "abbbbbc")
print(res)
# {m} 匹配m次 {m,n} 匹配m~n  {m,n}?
# res = re.match(r'ab{2,5}', "abbbbb")
# print(res)

# 7)或 |  a|b == [ab]
# res = re.match(r'a|b', "cbabc")
# print(res)
View Code
# 方法
# match
# search
# findall
# sub
# split
import re
# 从头开始,匹配一次(没有匹配到返回None)
# res = re.match(r'a', "abc")
# print(res)

# 匹配一次,无关位置,从前往后索引匹配(没有匹配到返回None)
res = re.search(r'a', "baca")
print(res)

# 从前往后索引匹配,匹配所有,返回列表(没有匹配到返回[])
res = re.findall(r'a', "baca")
print(res)

# 正则 替换字符串 目标字符串
# 不修改目标字符串,返回替换后的字符串
# ts = "abcdea"
# res = re.sub(r'[0-9]', "呵", "a2b12e9a")
# print(res)

# 以正则拆分成数据列表
# ts = "老男孩:python,Linux、H5、Java GO C++ AR VR"
# res = re.split(r' |:|,|、', ts)
# print(res)
View Code
# 分组()
# 1)分组不影响匹配结果 ((a(b)c)d(efg)) ==> abcdefg
# 2)0分组代表整体,第几个(就是第几位分组
import re
reg = r"((a(b)c)d(efg))"
ts = "abcdefg"
res = re.match(reg, ts)
print(res.group()) # abcdefg
print(res.group(0)) # abcdefg
print(res.group(1)) # abcdefg
print(res.group(2)) # abc
print(res.group(3)) # b
print(res.group(4)) # efg

# \num:num为分组号 \1 == book>
# reg = r"<(book>)(\w+)</\1"
# ts = "<book>语文</book>"
# res = re.match(reg, ts)
# print(res)

# (?P<mark>主体) (?P=mark)不占有分组
# reg = r"<(?P<tag>book>)(\w+)</(?P=tag)"
# ts = "<book>语文</book>"
# res = re.match(reg, ts)
# print(res.group(2))

# (?:) 取消分组
# [('语文', '</book>'), ('数学', '</book>')]
# reg = r"(?:<book>)(\w+)(</book>)"
# ts = "<book>语文</book><book>数学</book>"
# res = re.findall(reg, ts)
# print(res)
View Code

 

焚膏油以继晷,恒兀兀以穷年。
相关文章
|
15天前
|
机器学习/深度学习 存储 Python
|
22小时前
|
Python
【Python进阶(五)】——模块搜索及工作目录
【Python进阶(五)】——模块搜索及工作目录
|
2天前
|
Python Windows
python中的异常与模块
python中的异常与模块
9 1
|
12天前
|
JSON 数据格式 Python
Python标准库中包含了json模块,可以帮助你轻松处理JSON数据
【4月更文挑战第30天】Python的json模块简化了JSON数据与Python对象之间的转换。使用`json.dumps()`可将字典转为JSON字符串,如`{&quot;name&quot;: &quot;John&quot;, &quot;age&quot;: 30, &quot;city&quot;: &quot;New York&quot;}`,而`json.loads()`则能将JSON字符串转回字典。通过`json.load()`从文件读取JSON数据,`json.dump()`则用于将数据写入文件。
17 1
|
12天前
|
Python
Python实现压缩解压---tarfile模块详解
Python实现压缩解压---tarfile模块详解
|
13天前
|
Linux Python Windows
Python中time和datetime模块详解
Python中time和datetime模块详解
|
13天前
|
存储 Linux 数据安全/隐私保护
python的压缩模块zipfile详解
python的压缩模块zipfile详解
|
13天前
|
Linux Python Windows
python的os模块详细解读(二)
python的os模块详细解读(二)
|
13天前
|
移动开发 Linux Shell
python的os模块详细解读(一)
python的os模块详细解读(一)
python的os模块详细解读(一)
|
13天前
|
Python 容器
python内置函数、数学模块、随机模块(二)
python内置函数、数学模块、随机模块(二)