给出定义:

  1. re.sub(pattern, repl, string, count=0, flags=0)
  2.  
  3. Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. If the pattern isnt found, string is returned unchanged. repl can be a string or a function; if it is a string, any backslash escapes in it are processed. That is, \n is converted to a single newline character, \r is converted to a carriage return, and so forth. Unknown escapes such as \j are left alone. Backreferences, such as \6, are replaced with the substring matched by group 6 in the pattern. For example:
  4.  
  5. >>> re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):',
  6. ... r'static PyObject*\npy_\1(void)\n{',
  7. ... 'def myfunc():')
  8. 'static PyObject*\npy_myfunc(void)\n{'
  9. If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string. For example:
  10.  
  11. >>> def dashrepl(matchobj):
  12. ... if matchobj.group(0) == '-': return ' '
  13. ... else: return '-'
  14. >>> re.sub('-{1,2}', dashrepl, 'pro----gram-files')
  15. 'pro--gram files'
  16. >>> re.sub(r'\sAND\s', ' & ', 'Baked Beans And Spam', flags=re.IGNORECASE)
  17. 'Baked Beans & Spam'
  18. The pattern may be a string or an RE object.
  19.  
  20. The optional argument count is the maximum number of pattern occurrences to be replaced; count must be a non-negative integer. If omitted or zero, all occurrences will be replaced. Empty matches for the pattern are replaced only when not adjacent to a previous match, so sub('x*', '-', 'abc') returns '-a-b-c-'.
  21.  
  22. In addition to character escapes and backreferences as described above, \g<name> will use the substring matched by the group named name, as defined by the (?P<name>...) syntax. \g<number> uses the corresponding group number; \g<2> is therefore equivalent to \2, but isnt ambiguous in a replacement such as \g<2>0. \20 would be interpreted as a reference to group 20, not a reference to group 2 followed by the literal character '0'. The backreference \g<0> substitutes in the entire substring matched by the RE.
  23.  
  24. Changed in version 2.7: Added the optional flags argument.

  

re.sub的功能

re是regular expression的所写,表示正则表达式

sub是substitute的所写,表示替换;

re.sub是个正则表达式方面的函数,用来实现通过正则表达式,实现比普通字符串的replace更加强大的替换功能;

举个最简单的例子:

如果输入字符串是:

inputStr = "hello 111 world 111"
1
那么你可以通过

replacedStr = inputStr.replace("111", "222")
1
去换成

"hello 222 world 222"
1
但是,如果输入字符串是:

inputStr = "hello 123 world 456"
1
而你是想把123和456,都换成222

(以及其他还有更多的复杂的情况的时候),

那么就没法直接通过字符串的replace达到这一目的了。

就需要借助于re.sub,通过正则表达式,来实现这种相对复杂的字符串的替换:

replacedStr = re.sub("\d+", "222", inputStr)
1
当然,实际情况中,会有比这个例子更加复杂的,其他各种特殊情况,就只能通过此re.sub去实现如此复杂的替换的功能了。

所以,re.sub的含义,作用,功能就是:

对于输入的一个字符串,利用正则表达式(的强大的字符串处理功能),去实现(相对复杂的)字符串替换处理,然后返回被替换后的字符串

其中re.sub还支持各种参数,比如count指定要替换的个数等等。

下面就是来详细解释其各个参数的含义。

re.sub的各个参数的详细解释

re.sub共有五个参数。

re.sub(pattern, repl, string, count=0, flags=0)

其中三个必选参数:pattern, repl, string

两个可选参数:count, flags

第一个参数:pattern

pattern,表示正则中的模式字符串,这个没太多要解释的。

需要知道的是:

反斜杠加数字(\N),则对应着匹配的组(matched group)
比如\6,表示匹配前面pattern中的第6个group
意味着,pattern中,前面肯定是存在对应的,第6个group,然后你后面也才能去引用
比如,想要处理:

hello crifan, nihao crifan
1
且此处的,前后的crifan,肯定是一样的。

而想要把整个这样的字符串,换成crifanli

则就可以这样的re.sub实现替换:

inputStr = "hello crifan, nihao crifan";
replacedStr = re.sub(r"hello (\w+), nihao \1", "crifanli", inputStr);
1
2
第二个参数:repl

repl,就是replacement,被替换,的字符串的意思。

repl可以是字符串,也可以是函数。

repl是字符串

如果repl是字符串的话,其中的任何反斜杠转义字符,都会被处理的。

即:

\n:会被处理为对应的换行符;
\r:会被处理为回车符;
其他不能识别的转移字符,则只是被识别为普通的字符:
比如\j,会被处理为j这个字母本身;
反斜杠加g以及中括号内一个名字,即:\g,对应着命了名的组,named group
接着上面的举例:

想要把对应的:

hello crifan, nihao crifan
1
中的crifan提取出来,只剩:

crifan

就可以写成:

inputStr = "hello crifan, nihao crifan";
replacedStr = re.sub(r"hello (\w+), nihao \1", "\g<1>", inputStr);
print "replacedStr=",replacedStr; #crifan
1
2
3
对应的带命名的组(named group)的版本是:

inputStr = “hello crifan, nihao crifan”;
replacedStr = re.sub(r”hello (?P\w+), nihao (?P=name)”, “\g”, inputStr);
print “replacedStr=”,replacedStr; #crifan

repl是函数

举例说明:

比如输入内容是:

hello 123 world 456
1
想要把其中的数字部分,都加上111,变成:

hello 234 world 567
1
那么就可以写成:

  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3.  
  4. import re;
  5.  
  6. def pythonReSubDemo():
  7. """
  8. demo Pyton re.sub
  9. """
  10. inputStr = "hello 123 world 456";
  11.  
  12. def _add111(matched):
  13. intStr = matched.group("number"); #123
  14. intValue = int(intStr);
  15. addedValue = intValue + 111; #234
  16. addedValueStr = str(addedValue);
  17. return addedValueStr;
  18.  
  19. replacedStr = re.sub("(?P<number>\d+)", _add111, inputStr);
  20. print "replacedStr=",replacedStr; #hello 234 world 567
  21.  
  22. ###############################################################################
  23. if __name__=="__main__":
  24. pythonReSubDemo();

  

第三个参数:string

string,即表示要被处理,要被替换的那个string字符串。

没什么特殊要说明。

第四个参数:count

举例说明:

继续之前的例子,假如对于匹配到的内容,只处理其中一部分。

比如对于:

hello 123 world 456 nihao 789
1
只是像要处理前面两个数字:123,456,分别给他们加111,而不处理789,

那么就可以写成:

  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3.  
  4. import re;
  5.  
  6. def pythonReSubDemo():
  7. """
  8. demo Pyton re.sub
  9. """
  10. inputStr = "hello 123 world 456 nihao 789";
  11.  
  12. def _add111(matched):
  13. intStr = matched.group("number"); #123
  14. intValue = int(intStr);
  15. addedValue = intValue + 111; #234
  16. addedValueStr = str(addedValue);
  17. return addedValueStr;
  18.  
  19. replacedStr = re.sub("(?P<number>\d+)", _add111, inputStr, 2);
  20. print "replacedStr=",replacedStr; #hello 234 world 567 nihao 789
  21.  
  22. ###############################################################################
  23. if __name__=="__main__":
  24. pythonReSubDemo();

  

第五个参数:flags

关于re.sub的注意事项

要注意,被替换的字符串,即参数repl,是普通的字符串,不是pattern

注意到,语法是:

re.sub(pattern, repl, string, count=0, flags=0)
1
即,对应的第二个参数是repl。

需要你指定对应的r前缀,才是pattern:

r"xxxx"
1
不要误把第四个参数flag的值,传递到第三个参数count中了

否则就会出现我这里:

【已解决】Python中,(1)re.compile后再sub可以工作,但re.sub不工作,或者是(2)re.search后replace工作,但直接re.sub以及re.compile后再re.sub都不工作

遇到的问题:

当传递第三个参数,原以为是flag的值是,

结果实际上是count的值

所以导致re.sub不功能,

所以要参数指定清楚了:

replacedStr = re.sub(replacePattern, orignialStr, replacedPartStr, flags=re.I); # can omit count parameter
1
或:

replacedStr = re.sub(replacePattern, orignialStr, replacedPartStr, 1, re.I); # must designate count parameter
1
才可以正常工作。
---------------------
作者:Mrzhoug
来源:CSDN
原文:https://blog.csdn.net/mrzhoug/article/details/51585615
版权声明:本文为博主原创文章,转载请附上博文链接!

Python--详解Python中re.sub的更多相关文章

  1. Python | 详解Python中的协程,为什么说它的底层是生成器?

    今天是Python专题的第26篇文章,我们来聊聊Python当中的协程. 我们曾经在golang关于goroutine的文章当中简单介绍过协程的概念,我们再来简单review一下.协程又称为是微线程, ...

  2. 举例详解Python中的split()函数的使用方法

    这篇文章主要介绍了举例详解Python中的split()函数的使用方法,split()函数的使用是Python学习当中的基础知识,通常用于将字符串切片并转换为列表,需要的朋友可以参考下   函数:sp ...

  3. 详解Python中re.sub--转载

    [背景] Python中的正则表达式方面的功能,很强大. 其中就包括re.sub,实现正则的替换. 功能很强大,所以导致用法稍微有点复杂. 所以当遇到稍微复杂的用法时候,就容易犯错. 所以此处,总结一 ...

  4. 详解Python编程中基本的数学计算使用

    详解Python编程中基本的数学计算使用 在Python中,对数的规定比较简单,基本在小学数学水平即可理解. 那么,做为零基础学习这,也就从计算小学数学题目开始吧.因为从这里开始,数学的基础知识列位肯 ...

  5. 详解Python中内置的NotImplemented类型的用法

    它是什么? ? 1 2 >>> type(NotImplemented) <type 'NotImplementedType'> NotImplemented 是Pyth ...

  6. [转载]python 详解re模块

    原文地址:python 详解re模块作者:Rocky 正则表达式的元字符有. ^ $ * ? { [ ] | ( ) .表示任意字符 []用来匹配一个指定的字符类别,所谓的字符类别就是你想匹配的一个字 ...

  7. 33 Python 详解命令解析 - argparse--更加详细--转载

    https://blog.csdn.net/lis_12/article/details/54618868 Python 详解命令行解析 - argparse Python 详解命令行解析 - arg ...

  8. 详解Python模块导入方法

    python常被昵称为胶水语言,它能很轻松的把用其他语言制作的各种模块(尤其是C/C++)轻松联结在一起.python包含子目录中的模块方法比较简单,关键是能够在sys.path里面找到通向模块文件的 ...

  9. 详解python函数的参数

    详解python函数的参数 一.参数的定义 1.函数的参数在哪里定义 在python中定义函数的时候,函数名后面的括号里就是用来定义参数的,如果有多个参数的话,那么参数之间直接用逗号, 隔开 案列: ...

  10. 详解Python函数参数定义及传参(必备参数、关键字参数、默认可省略参数、可变不定长参数、*args、**kwargs)

    详解Python函数参数定义及传参(必备参数.关键字参数.默认可省略参数.可变不定长参数.*args.**kwargs) Python函数参数传参的种类   Python中函数参数定义及调用函数时传参 ...

随机推荐

  1. github总结(3)--怎样在github上面实现页面托管

    part Ⅱ:gh-pages分支--实现页面托管 第一步:在github线上创建一个新的仓库 第二步:在项目本地地址,git init初始化,再git add --all进行文档追踪添加 第三步:g ...

  2. 解决使用elementUI框架el-upload上传组件时session丢失问题

    在使用elementui框架上传组件的时候,出现session丢失,后端无法获取到sessionid,导致返回状态为未登陆 查看请求头缺少cookie值 上传组件代码: <el-upload c ...

  3. ModBus通信协议的【传输方式】

    1.Modbus 传输方式 标准的Modbus口是使用一RS-232C兼容串行接口,它定义了连接口的针脚.电缆.信号位.传输波特率.奇偶校验.控制器能直接或经由Modem组网.     控制器通信使用 ...

  4. anaconda更新库命令

    输入y更新库

  5. [android] 手机卫士设备管理权限锁屏

    设备管理员 Device Admin 获取DevicePolicyManager对象,通过getSystemService(DEVICE_POLICY_MANAGER),设备策略管理器 调用Devic ...

  6. cordova启动页面和图标的设置

    一.config.xml配置 在cordova5.0版本以后,需要安装cordova-plugin-splashscreen插件以后才能修改和设置App的启动页面. 安装splashscreen插件: ...

  7. CSS中你知道的display的值有多少?用了多少?

    它的语法如下: display:none | inline | block | list-item | inline-block | table | inline-table | table-capt ...

  8. Java执行sh等

    1.通过java代码,调用bat.shell等脚本或者命令 1)使用Runtime的exec()方法,会返回一个用于管理操作系统进程的Process对象 Process process =null; ...

  9. putty之pscp上传文件

    控制台下打开pscp可执行文件 命令 >pscp -i 证书名 -r 要上传的文件 root@服务器路径:/opt

  10. php使用PHPexcel类读取excel文件(循环读取每个单元格的数据)

    error_reporting(E_ALL); date_default_timezone_set('Asia/ShangHai'); include_once('Classes/PHPExcel/I ...