[关闭]
@zhangyu756897669 2017-09-08T15:40:48.000000Z 字数 2462 阅读 503

python

python 官方文档


点与星号组合 .*

有些时候,你想要匹配一切东西, 例如,假设您要匹配字符串“名字:”,后跟任何和所有文本,后跟“姓氏:”,然后再次跟随。您可以使用点星(. *)来代替“任何东西”。请记住,点字符表示“除换行之外的任何单个字符”,星号表示“前一个字符的零个或多个”。

  1. import re
  2. nameRegex = re.compile(r'First Name: (.*) Last Name: (.*)')
  3. mo = nameRegex.search('First Name: Al Last Name: Sweigart')
  4. mo.group(1)

'Al'

  1. mo.group(2)

'Sweigart'

  1. nongreedyRegex = re.compile(r'<.*?>')
  2. mo = nongreedyRegex.search('<To serve man> for dinner.>')
  3. mo.group()

'<To serve man>'

  1. greedyRegex = re.compile(r'<.*>')
  2. mo = greedyRegex.search('<To serve man> for dinner.>')
  3. mo.group()

'<To serve man> for dinner.>'

匹配换行符与点字符

  1. noNewlineRegex = re.compile('.*')
  2. noNewlineRegex.search('Serve the public trust.\nProtect the innocent.\nUphold the law.').group()

'Serve the public trust.'

  1. newlineRegex = re.compile('.*', re.DOTALL)
  2. newlineRegex.search('Serve the public trust.\nProtect the innocent.\nUphold the law.').group()

'Serve the public trust.\nProtect the innocent.\nUphold the law.'

审查正则符号

本章涵盖了很多符号,所以这里快速回顾一下你学到的内容:

不区分大小写匹配

通常,正则表达式将文本与您指定的确切套件相匹配。例如,以下正则表达式完全匹配不同的字符串:

  1. regex1 = re.compile('Robocop')
  2. regex2 = re.compile('ROBOCOP')
  3. regex3 = re.compile('robOcop')
  4. regex4 = re.compile('RobocOp')
  1. robocop = re.compile(r'robocop', re.I)
  2. robocop.search('Robocop is part man, part machine, all cop.').group()

'Robocop'

  1. robocop.search('ROBOCOP protects the innocent.').group()

'ROBOCOP'

  1. robocop.search('Al, why does your programming book talk about robocop so much?').group()

'robocop'

用sub()方法代替字符串

正则表达式不仅可以查找文本模式,还可以替换新文本来代替这些模式。 Regex对象的sub()方法传递两个参数。第一个参数是用于替换任何匹配的字符串。第二个是正则表达式的字符串。 sub()方法返回一个应用了替换的字符串。

  1. namesRegex = re.compile(r'Agent \w+')
  2. namesRegex.sub('CENSORED', 'Agent Alice gave the secret documents to Agent Bob.')

'CENSORED gave the secret documents to CENSORED.'

  1. agentNamesRegex = re.compile(r'Agent (\w)\w*')
  2. 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.'

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注