python正则表达式re模块详解

yipeiwu_com6年前Python基础

快速入门

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

相关文章

numpy库与pandas库axis=0,axis= 1轴的用法详解

numpy库与pandas库axis=0,axis= 1轴的用法详解

对数据进行操作时,经常需要在横轴方向或者数轴方向对数据进行操作,这时需要设定参数axis的值: axis = 0 代表对横轴操作,也就是第0轴; axis = 1 代表对纵轴操...

Python Pandas批量读取csv文件到dataframe的方法

Python Pandas批量读取csv文件到dataframe的方法

PYTHON Pandas批量读取csv文件到DATAFRAME 首先使用glob.glob获得文件路径。然后定义一个列表,读取文件后再使用concat合并读取到的数据。 #读取数...

Python进程间通信用法实例

本文实例讲述了Python进程间通信用法。分享给大家供大家参考。具体如下: #!/usr/bin/env python # -*- coding=utf-8 -*- import m...

Python创建一个空的dataframe,并循环赋值的方法

如下所示: # 创建一个空的 DataFrame df_empty = pd.DataFrame() #或者 df_empty = pd.DataFrame(columns=['A'...

python模拟实现斗地主发牌

题目:趣味百题之斗地主 扑克牌是一种非常大众化的游戏,在计算机中有很多与扑克牌有关的游戏。例如,在Windows操作系统下自带的纸牌、红心大战等。在扑克牌类的游戏中,往往都需要执行洗牌操...