Python学习笔记模式匹配与正则表达式之统配字符

随笔记录方便自己和同路人查阅。

#------------------------------------------------我是可耻的分割线-------------------------------------------

  在正则表达式中,.(句点)字符称为“通配符”。它匹配除了换行之外的所有字符。

#------------------------------------------------我是可耻的分割线-------------------------------------------

  1、句点统配字符匹配单个字符,示例代码: 

#! python 3
# -*- coding:utf-8 -*-
# Autor: Li Rong Yang
import re
atRegex = re.compile(r'.at')#使用句号匹配at前面的单个字符
mo = atRegex.findall('The cat in the hat sat on the flat mat.')#检查文本内容
print(mo)#输出符合条件的内容

  运行结果:

要记住,句点字符只匹配一个字符,这就是为什么在前面的例子中,对于文本flat,只匹配 lat。要匹配真正的句点,就是用倒斜杠转义:\.。

   2、句点-星号匹配所有字符,有时候想要匹配所有字符串。例如,假定想要匹配字符串'First Name:',接下来是任意文本,接下来是

'Last Name:',然后又是任意文本。可以用点-星(.*)表示“任意文本”。回忆一下,句点字符表示“除换行外所有单个字符”,星号字符表示

“前面字符出现零次或多次”。

  示例代码:

#! python 3
# -*- coding:utf-8 -*-
# Autor: Li Rong Yang
import re
atRegex = re.compile(r'First Name: (.*) Last Name: (.*)')#使用句-星号匹配所有字符
mo = atRegex.findall('First Name: Al Last Name: Sweigart')#检查文本内容
print(mo)#输出符合条件的内容

  运行结果:

  点-星使用“贪心”模式:它总是匹配尽可能多的文本。要用“非贪心”模式匹配所有文本,就使用点-星和问号。像和大括号一起使用时那样,

问号告诉Python 用非贪心模式匹配。

  示例代码:

#! python 3
# -*- coding:utf-8 -*-
# Autor: Li Rong Yang
import re
nongreedyRegex = re.compile(r'<.*?>')#非贪心模式
mo = nongreedyRegex.search('<To serve man> for dinner.>')#检查文本内容
print(mo)#输出符合条件的内容

import re
nongreedyRegex = re.compile(r'<.*>')#贪心模式
mo = nongreedyRegex.search('<To serve man> for dinner.>')#检查文本内容
print(mo)#输出符合条件的内容

  运行结果:

  3、句点字符匹配换行,点-星将匹配除换行外的所有字符。通过传入 re.DOTALL 作为 re.compile()的第二个参数,可以让句点字符匹配所有字符,

包括换行字符。

  未使用re.DOTALL参数, 示例代码: 

#! python 3
# -*- coding:utf-8 -*-
# Autor: Li Rong Yang
import re
noNewlineRegex = re.compile('.*')#非贪心模式
mo = noNewlineRegex.search('Serve the public trust.\nProtect the innocent.\nUphold the law.').group()#检查文本内容
print(mo)#输出符合条件的内容

  运行结果:

  使用re.DOTALL参数, 示例代码: 

#! python 3
# -*- coding:utf-8 -*-
# Autor: Li Rong Yang
import re
noNewlineRegex = re.compile('.*', re.DOTALL)#非贪心模式
mo = noNewlineRegex.search('Serve the public trust.\nProtect the innocent.\nUphold the law.').group()#检查文本内容
print(mo)#输出符合条件的内容

  运行结果:

猜你喜欢

转载自www.cnblogs.com/lirongyang/p/9580663.html