博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python 基础 8.4 re的 spilt() findall() finditer() 方法
阅读量:7013 次
发布时间:2019-06-28

本文共 1443 字,大约阅读时间需要 4 分钟。

 
#/usr/bin/python
#coding=utf-8
#@Time   :2017/11/18 18:24
#@Auther :liuzhenchuan
#@File   :re的split findall  finditer 方法.py
import re
 
#re.compile 将正则表达式编译成对象
#split() 方法,是分割
p = re.compile(r'\d+')
a_str = 'one1two2three3foure4'
 
#把p的正则当成分隔符,把字符串用p进行割,最后返回
print '###'*5 + '以数字\d进行分隔' + '###'*5
print p.split('one1two2three3foure4')
 
#使用正则匹配分隔字符串
print p.split(a_str)
 
print '###'*30 + '\n'
#以空白字符进行分隔
print'###'*5 + '以空白字符\s进行分隔' + '###'*5
m = re.compile(r'\s+')
print m.split('123 456 7890 890')
 
# #以非单词进行分隔
print '###'*5 + '以非单词串进行分隔' + '###'*5
n = re.compile(r'\W+')
print n.split('1234**4567P890**op')
 
print '###'*30 + '\n'
##正则对象findall() ,来查找符合对象的字符串.以列表的形式返回
print '查找符合纯数字的'
p = re.compile(r'\d+')
a_str = 'one1two2three3foure4'
print p.findall(a_str)
print '###'*5 + '\n'
 
print 'finditer()方法'
#finditer()方法,finditer可迭代的对象,可迭代的方法比findall方法好
for i in p.finditer(a_str):
    print i.group()
 
>>>
###############以数字\d进行分隔###############
['one', 'two', 'three', 'foure', '']
['one', 'two', 'three', 'foure', '']
##########################################################################################
 
###############以空白字符\s进行分隔###############
['123', '456', '7890', '890']
###############以非单词串进行分隔###############
['1234', '4567P890', 'op']
##########################################################################################
 
查找符合纯数字的
['1', '2', '3', '4']
###############
 
finditer()方法
1
2
3
4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

转载于:https://www.cnblogs.com/lzcys8868/p/7858132.html

你可能感兴趣的文章
与继承相关的一些重构(二)
查看>>
22 UI_布局之线性布局-动态生成与LayoutInflater
查看>>
关于三元运算符的一个问题
查看>>
11.04T1 枚举
查看>>
滑雪 记忆化搜索简单模型
查看>>
生成随机字符串 可以用在项目上作为 单号之类的
查看>>
简单的 canvas 翻角效果
查看>>
window 7 下面解决修改hosts文件
查看>>
android笔试题二
查看>>
TP5数据库操作方法
查看>>
qu(判定操作序列)NOIP模拟 数据结构判断 模拟
查看>>
Linux杂学
查看>>
更新SVN时提示要清理,但清理失败,乱码得解决方案
查看>>
连接mysql数据库,创建用户模型
查看>>
Nhibernate总结(一)查询返回指定字段
查看>>
Uva 10106 - Product
查看>>
Uva 101 - The Blocks Problem
查看>>
Eclipse 调试Bug之使用断点的七大技巧
查看>>
APP在用户设备发生crash,应该怎么修复
查看>>
Nodejs项目重复文件扫描
查看>>