Python 正则表达
2017-05-30 20:36
591 查看
1.match和search的区别
def re_method(): # search vs. Match s = 'abcd' print(re.search(r'c', s)) print(re.match(r'c', s)) if __name__ == '__main__': re_method()
返回值为
<_sre.SRE_Match object; span=(2, 3), match='c'> None
match从字符串的第一个开始进行匹配,可以通过在前面加
.*的方式找到,其中
.表示匹配任意字符
如
re.match(r'.*c', s)
search:搜索字符串任意位置的匹配,可以通过添加
^^表示某一字符串的开始位置
如
re.search(r'^c', s)
2.split
分割字符,按照非字母字符re.split(r'\W+','I love you')
[‘I’, ‘love’, ‘you’]
\W:表示非字母字符,\w:表示字母字符,如果按照\w分割,那么会是另一种结果
3.findall和finditer
findall根据正则表达式从左到右搜索匹配项,返回匹配的字符串列表(跟search是对应的关系,search是只要搜索到匹配的第一个,它就会停下来,findall是会继续往下查找)re.findall(r'\w+','I love you')
输出
['I', 'love', 'you']
re.findall(r'\d+\.?\d*', 'The beef is $5.6,I like to take 2 piece',)
输出
[5.6 2]
finditer根据正则表达式从左到右搜索匹配项,返回一个迭代器迭代返回MatchObjec
def re_demo(): s = 'The first price is $9.90 and the second price is $100' i = re.finditer(r'\d+\.?\d*', s) for m in i: print(m.group()) re_demo()
4.sub和subn
字符串替换字符串替换s = 'The first price is $9.90 and the second price is $100' print(re.sub(r"\$\d+\.?\d*",'<number>',s))
subn和sub一样:返回值多了替换的字符串个数
相关文章推荐
- Python 语言及其应用 Chapter_7_Note 1 正则表达匹配
- python正则表达学习
- Python 基础 —— re:正则表达
- Python正则表达所用到的符号
- Python 正则表达试
- python中的正则表达示
- Python--正则表达模块re
- Python 从文件中筛选出ip 正则表达(re)
- python 基本的正则表达
- Python-网络爬虫之正则表达
- python正则表达
- 【转】python中的正则表达示
- python 正则表达 10分钟入门
- python的re正则表达
- python的正则表达一
- python——re模块(正则表达)
- Python正则表达
- python处理图像标签、正则表达
- python正则表达
- 一文详解Python正则表达(3.X版本)