您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python正则表达式re模块详解

5b51 2022/1/14 8:18:31 python 字数 2055 阅读 343 来源 www.jb51.cc/python

快速入门 importre pattern=\'this\' text=\'Doesthistextmatchthepattern?\' match=re.search(pattern,text)

概述

快速入门

import re

pattern = 'this'
text = 'Does this text match the pattern?'

match = re.search(pattern,text)

s = match.start()
e = match.end()

print('Found "{0}"\nin "{1}"'.format(match.re.pattern,match.string))
print('from {0} to {1} ("{2}")'.format( s,e,text[s:e]))

执行结果:

#python re_simple_match.py 
Found "this"
in "Does this text match the pattern?"
from 5 to 9 ("this")
import re

# Precompile the patterns
regexes = [ re.compile(p) for p in ('this','that')]
text = 'Does this text match the pattern?'

print('Text: {0}\n'.format(text))

for regex in regexes:
  if regex.search(text):
    result = 'match!'
  else:
    result = 'no match!'
    
  print('Seeking "{0}" -> {1}'.format(regex.pattern,result))

执行结果:

#python re_simple_compiled.py 
Text: Does this text match the pattern?

Seeking "this" -> match!
Seeking "that" -> no match!

import re

text = 'abbaaabbbbaaaaa'

pattern = 'ab'

for match in re.findall(pattern,text):
  print('Found "{0}"'.format(match))

执行结果:

#python re_findall.py 
Found "ab"
Found "ab"

import re

text = 'abbaaabbbbaaaaa'

pattern = 'ab'

for match in re.finditer(pattern,text):
  s = match.start()
  e = match.end()
  print('Found "{0}" at {1}:{2}'.format(text[s:e],s,e))

执行结果:

#python re_finditer.py 
Found "ab" at 0:2
Found "ab" at 5:7

总结

以上是编程之家为你收集整理的python正则表达式re模块详解全部内容,希望文章能够帮你解决python正则表达式re模块详解所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶