python正则表达式 Python Re模块
2016-06-06 16:31
471 查看
最近在学python 练习的时候随手写的,方便以后自己参考~如果能对其他同学有所帮助就再好不过了
[b]希望大家指正哦~ 我会随时整理的,先这样~[/b][b]正则表达式[/b]
1.元字符([ ]),它用来指定一个character class。所谓character classes就是你想要匹配的字符(character)的集合.字符(character)可以单个的列出,也可以通过"-"来分隔两个字符来表示一个范围。例如,[abc]匹配a,b或者c当中任意一个字符,[abc]也可以用字符区间来表示---[a-c].如果想要匹配单个大写字母,你可以用[A-Z]。
元字符(metacharacters)在character class里面不起作用,如[akm$]将匹配"a","k","m","$"中的任意一个字符。在这里元字符(metacharacter)"$"就是一个普通字符。
2.元字符[^]. 你可以用补集来匹配不在区间范围内的字符。其做法是把"^"作为类别的首个字符;其它地方的"^"只会简单匹配 "^"字符本身。例如,[^5] 将匹配除 "5" 之外的任意字符。同时,在[ ]外,元字符^表示匹配字符串的开始,如"^ab+"表示以ab开头的字符串。
pattern = re.compile(r'\W+')
print re.findall(pattern, '/one1two*2three3four4!')
### 输出 ###
# ['/', '*', '!']
搜索string,返回一个顺序访问每一个匹配结果
\w:代表字母数字下划线
(6)re.sub(pattern, repl, string[, count])
对匹配的文本 用repl 替换 这里的\2(\id)代表的是第二个分组 0分组是整个文本!!!第一个左括号是第一个分组pattern = re.compile(r'(\w+) (\w+)') s = 'i say, hello world!' 你看这里的第一个分组就是i 第二个分组是say
print re.sub(pattern,r'\2 \1', s) 用say i替换i say
在这个例子里的 func函数用的挺巧妙
.title是使得第一字母大写?~~?!
import re pattern = re.compile(r'(\w+) (\w+)') s = 'i say, hello world!' print re.sub(pattern,r'\2 \1', s) def func(m): return m.group(1).title() + ' ' + m.group(2).title() print re.sub(pattern,func, s) ### output ### # say i, world hello! # I Say, Hello World!
re.subn(pattern, repl, string[, count])
只是输出结果中有一个替换次数输出结果对比
say i, world hello!
I Say, Hello World!
('say i, world hello!', 2)
('I Say, Hello World!', 2)
SET(不重复)
s = set(['Adam', 'Lisa', 'Bart', 'Paul']) #创建 set 的方式是调用 set() 并传入一个 list,list的元素将作为set的元素 s是set集合创建的一个对象
s = set(['Adam', 'Lisa', 'Bart', 'Paul'])
print 'Bart' in s
输出:true
可以用“in”来判
相关文章推荐
- windows下安装numpy,scipy遇到的问题总结
- 深入理解python函数递归和生成器
- python dataframe 针对多列执行map操作
- Python 入门:字符串连接及join用法
- python下调用pytesseract识别某网站验证码的实现方法
- 利用python进行数据分析ch02(usa.gob)
- leetcode 275. H-Index II-h因子|二分查找
- python定时杀进程
- ubuntu下搭建Python开发环境(eclipse+pydev)
- 112. Path Sum [easy] (Python)
- 误删python setuptools的解决方案
- Python正则匹配 -> 模块和基本函数
- python生成器(转)
- Python实现MySQL DBA小工具一例 推荐
- 浅析AST抽象语法树及Python代码实现
- python set
- python logging使用
- Python学习笔记 —— 数字类型【Numbers】及常用方法
- Python装饰器与面向切面编程
- Python字符编码