@zhangyu756897669
2017-09-08T15:40:48.000000Z
字数 2462
阅读 503
python
官方文档
有些时候,你想要匹配一切东西, 例如,假设您要匹配字符串“名字:”,后跟任何和所有文本,后跟“姓氏:”,然后再次跟随。您可以使用点星(. *)来代替“任何东西”。请记住,点字符表示“除换行之外的任何单个字符”,星号表示“前一个字符的零个或多个”。
import re
nameRegex = re.compile(r'First Name: (.*) Last Name: (.*)')
mo = nameRegex.search('First Name: Al Last Name: Sweigart')
mo.group(1)
'Al'
mo.group(2)
'Sweigart'
nongreedyRegex = re.compile(r'<.*?>')
mo = nongreedyRegex.search('<To serve man> for dinner.>')
mo.group()
'<To serve man>'
greedyRegex = re.compile(r'<.*>')
mo = greedyRegex.search('<To serve man> for dinner.>')
mo.group()
'<To serve man> for dinner.>'
noNewlineRegex = re.compile('.*')
noNewlineRegex.search('Serve the public trust.\nProtect the innocent.\nUphold the law.').group()
'Serve the public trust.'
newlineRegex = re.compile('.*', re.DOTALL)
newlineRegex.search('Serve the public trust.\nProtect the innocent.\nUphold the law.').group()
'Serve the public trust.\nProtect the innocent.\nUphold the law.'
本章涵盖了很多符号,所以这里快速回顾一下你学到的内容:
通常,正则表达式将文本与您指定的确切套件相匹配。例如,以下正则表达式完全匹配不同的字符串:
regex1 = re.compile('Robocop')
regex2 = re.compile('ROBOCOP')
regex3 = re.compile('robOcop')
regex4 = re.compile('RobocOp')
robocop = re.compile(r'robocop', re.I)
robocop.search('Robocop is part man, part machine, all cop.').group()
'Robocop'
robocop.search('ROBOCOP protects the innocent.').group()
'ROBOCOP'
robocop.search('Al, why does your programming book talk about robocop so much?').group()
'robocop'
正则表达式不仅可以查找文本模式,还可以替换新文本来代替这些模式。 Regex对象的sub()方法传递两个参数。第一个参数是用于替换任何匹配的字符串。第二个是正则表达式的字符串。 sub()方法返回一个应用了替换的字符串。
namesRegex = re.compile(r'Agent \w+')
namesRegex.sub('CENSORED', 'Agent Alice gave the secret documents to Agent Bob.')
'CENSORED gave the secret documents to CENSORED.'
有时您可能需要使用匹配的文本本身作为替代的一部分。在sub()的第一个参数中,您可以键入\ 1,\ 2,\ 3等等,以表示“替换”中输入组1,2,3等的文本。
例如,你想通过显示名字的第一个字母来检查秘密特工的名字。为此,您可以使用正则表达式代理(\ w)\ w *,并将r'\ 1 ****'作为sub()的第一个参数。该字符串中的\ 1将被组1匹配的任何文本替换,即正则表达式的(\ w)组。
agentNamesRegex = re.compile(r'Agent (\w)\w*')
agentNamesRegex.sub(r'\1****', 'Agent Alice told Agent Carol that Agent Eve knew Agent Bob was a double agent.')
'A**** told C**** that E**** knew B**** was a double agent.'