加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python正则表达式re模块详解

发布时间:2020-12-16 20:14:51 所属栏目:Python 来源:网络整理
导读:快速入门 import repattern = '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}")'.f

快速入门

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读