当前位置: 移动技术网 > IT编程>脚本编程>Python > python正则表达式re模块详解

python正则表达式re模块详解

2019年03月29日  | 移动技术网IT编程  | 我要评论

41aaa,快乐驿站下载,11岁的少女

快速入门

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网