python正则表达式 re (二)sub
来源:互联网 发布:七匣子淘宝 编辑:程序博客网 时间:2024/05/22 05:19
背景:
re.sub是re模块重要的组成部分,并且功能也非常强大,主要功能实现正则的替换。
re.sub定义:
sub(pattern, repl, string, count=0, flags=0)
Return the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in string by the
replacement repl. repl can be either a string or a callable;
if a string, backslash escapes in it are processed. If it is
a callable, it’s passed the match object and must return
a replacement string to be used.
主要的意思为:对字符串string按照正则表达式pattern,将string的匹配项替换成字符串repl。
公式解析:
pattern为表示正则中的模式字符串,
repl为replacement,被替换的内容,repl可以是字符串,也可以是函数。
string为正则表达式匹配的内容。
count:由于正则表达式匹配到的结果是多个,使用count来限定替换的个数(顺序为从左向右),默认值为0,替换所有的匹配到的结果。
flags是匹配模式,可以使用按位或’|’表示同时生效,也可以在正则表达式字符串中指定。(详情见链接)
举例:
>import re>re.sub(r'\w+','10',"ji 43 af,geq",2,flags=re.I)'10 10 af,geq'
详解:首先导入re模块,使用re.sub函数,r’\w+’为正则表达式,匹配英文单词或数字,’10’为被替换的内容,”ji 43 af,geq”为re匹配的字符串内容,count为2 只替换前两个,flags=re.I 忽略大小写。
输出部分自行理解。
- python正则表达式 re (二)sub
- python正则表达式 re (二)compile
- python正则表达式 re (二)split
- python正则表达式 re (二)escape
- python正则表达式模块,re.sub的函数使用
- python中re.sub的使用 正则表达式
- python re.sub 正则匹配
- Python正则表达式学习(1)——re.sub()基础
- python正则表达式(re)
- python正则表达式 re (二)match与search
- python正则表达式 re (二)findall与finditer
- python正则表达式 re (二)匹配对象和组
- Python 正则表达式 sub
- python re 正则表达式之二
- python正则替换操作re.sub()
- Python 正则表达式 re
- python-re【正则表达式】
- python re 正则表达式
- poj3320
- SQL truncate 、delete与drop区别
- web.xml
- zigbee术语简介
- session与request
- python正则表达式 re (二)sub
- C# 反射
- 杭电 1503 Advanced Fruits(lcs)
- C++11 并发指南六( <atomic> 类型详解二 std::atomic )
- java连接数据库核心代码
- codeforce 315 div2
- 【黑马程序员-学习笔记】数据结构-树与图
- Android Studio 运行项目遇到的错误
- 19-集合框架工具类-16-常用对象API(集合框架-工具类-Collections-其他方法&将非同步集合转成同步集合的方法)