python3正则表达式
来源:互联网 发布:帝豪 gs 知乎 编辑:程序博客网 时间:2024/05/17 07:03
正则表达式是一个特殊的字符序列,它能帮助你方便的检查一个字符串是否与某种模式匹配。re 模块使 Python 语言拥有全部的正则表达式功能。
import re#re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;而re.search匹配整个字符串,直到找到一个匹配。#re.match 尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回none。print(re.match('www', 'www.runoob.com').span())#不在起始位置匹配print(re.match('com', 'www.runoob.com'))line = 'Cat are smarter than dogs'matchObj = re.match(r'(.*) are (.*?) (.*)', line, re.M|re.I)if matchObj: print("matchObj.group() : ", matchObj.group()) print("matchObj.group(1) : ", matchObj.group(1)) print("matchObj.group(2) : ", matchObj.group(2)) print("matchObj.group(3) : ", matchObj.group(3))else: print("No match!!")#re.search 扫描整个字符串并返回第一个成功的匹配。print(re.search('www', 'www.runoob.com').span())#不在起始位置匹配print(re.search('com', 'www.runoob.com').span())#re.sub用于替换字符串中的匹配项phone = "2004-959-559 # 这是一个电话号码"#删除注释num = re.sub(r'#.*$', '', phone)print('电话号码:', num)#移除非数字的内容num = re.sub(r'\D', '', phone)print('电话号码:', num)
运行结果:
D:\python3.6.1\python.exe F:/python_Advanced/pattern.py
(0, 3)
None
matchObj.group() : Cat are smarter than dogs
matchObj.group(1) : Cat
matchObj.group(2) : smarter
matchObj.group(3) : than dogs
(0, 3)
(11, 14)
电话号码: 2004-959-559
电话号码: 2004959559
Process finished with exit code 0
阅读全文
0 0
- Python3:正则表达式
- Python3 re(正则表达式)
- python3正则表达式
- python3之正则表达式
- Python3正则表达式
- Python3 正则表达式
- Python3 re(正则表达式)
- Python3正则表达式
- Python3正则表达式使用
- Python3.x 正则表达式
- Python3正则表达式(Python3 Regular Expression)
- Python3之正则表达式详解
- python3使用正则表达式小记
- python3 常用正则匹配表达式
- python3爬虫之入门和正则表达式
- 正则表达式 python3.x (一)
- Python3-正则表达式-创建、匹配Regex对象
- Python3爬虫之入门和正则表达式
- Linux 中shell脚本/eval调研
- RTT使用固定地址的方法
- test
- border-image用法
- 使用spring RestTemplate进行rest接口测试
- python3正则表达式
- 面向对象习题(一)
- HTML-简单的遮罩层实现
- web测试方法总结
- cookie和session的区别
- scala(8)-----循环
- iOS Xcode在运行时总是提示输入用户名和密码
- 反射
- 对Minor GC和Major GC做点笔记