热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何在Python2.7中使用带有IGNORECASE的re.sub?-HowcanIusere.subwithIGNORECASEinPython2.7?

Iwanttomodifyastringwiththehelpofre.sub:我想在re.sub的帮助下修改一个字符串:>>>re.sub(spart

I want to modify a string with the help of re.sub:

我想在re.sub的帮助下修改一个字符串:

>>> re.sub("sparta", r"\1", "Here is Sparta.", flags=re.IGNORECASE)

I expect to get:

我希望得到:

'Here is Sparta.'

But I get an error instead:

但我得到一个错误:

>>> re.sub("sparta", r"\1", "Here is Sparta.", flags=re.IGNORECASE)
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/lib/python2.7/re.py", line 155, in sub
    return _compile(pattern, flags).sub(repl, string, count)
  File "/usr/lib/python2.7/re.py", line 291, in filter
    return sre_parse.expand_template(template, match)
  File "/usr/lib/python2.7/sre_parse.py", line 833, in expand_template
    raise error, "invalid group reference"
sre_constants.error: invalid group reference

How should I use re.sub to get the correct result?

我该如何使用re.sub来获得正确的结果?

2 个解决方案

#1


2  

You do not specify any capturing group in the pattern and use a backreference to Group 1 in the replacement pattern. That causes an issue.

您不在模式中指定任何捕获组,并在替换模式中对组1使用反向引用。这导致了一个问题。

Either define a capturing group in the pattern and use the appropriate backreference in the replacement pattern, or use the \g<0> backreference to the whole match:

在模式中定义捕获组并在替换模式中使用适当的反向引用,或使用\ g <0>反向引用整个匹配:

re.sub("sparta", r"\g<0>", "Here is Sparta.", flags=re.IGNORECASE)

See the Python demo.

请参阅Python演示。

#2


0  

When you use \x in your second string (replacement string I think it's called) where x is a number, python is going to replace it with the group x.

当您在第二个字符串中使用\ x(替换字符串,我认为它被称为),其中x是一个数字,python将用组x替换它。

You can define a group in your regex by wrapping it with parentheses, like so:

您可以通过用括号括起来在正则表达式中定义一个组,如下所示:

re.sub(r"capture (['me]{2})", r'group 1: \1', 'capture me!') # => group 1: me
re.sub(r"capture (['me]{2})", r'group 1: \1', "capture 'em!") # => group 1: 'em

Nested captures? I've lost the count!

嵌套捕获?我输掉了数!

It's the opening bracket that defines it's number:

它是定义它的数字的开始括号:

(this is the first group (this is the second) (this is the third))

Named group

Named group are pretty useful when you use the match object that returns re.match or re.search for example (refer to the docs for more), but also when you use complex regex, because they bring clarity.

当您使用返回re.match或re.search的匹配对象时,命名组非常有用(请参阅文档了解更多信息),以及使用复杂正则表达式时,因为它们带来了清晰度。

You can name a group with the following syntax:

您可以使用以下语法命名组:

(?Pyour pattern)

So, for example:

所以,例如:

re.sub("(?Phello(?P[test]+)) (?P[a-z])", "first: \g") # => first: hello

What is the group 0

The group 0 is the entire match. But, you can't use \0, because it's going to print out \x00 (the actual value of this escaped code). The solution is to use the named group syntax (because regular group are kind of named group: they're name is just an integer): \g<0>. So, for example:

组0是整场比赛。但是,您不能使用\ 0,因为它将打印出\ x00(此转义代码的实际值)。解决方案是使用命名的组语法(因为常规组是一种命名组:它们的名称只是一个整数):\ g <0>。所以,例如:

re.sub(r'[hello]+', r'\g<0>', 'lehleo') # => lehleo

For your problem

This answer is just suppose to explain capturing, not really answering your question, since @Wiktor Stribiżew's one is perfect.

这个答案只是假设解释捕获,而不是真正回答你的问题,因为@WiktorStribiżew的一个是完美的。


推荐阅读
  • Python正则表达式学习记录及常用方法
    本文记录了学习Python正则表达式的过程,介绍了re模块的常用方法re.search,并解释了rawstring的作用。正则表达式是一种方便检查字符串匹配模式的工具,通过本文的学习可以掌握Python中使用正则表达式的基本方法。 ... [详细]
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • 本文主要解析了Open judge C16H问题中涉及到的Magical Balls的快速幂和逆元算法,并给出了问题的解析和解决方法。详细介绍了问题的背景和规则,并给出了相应的算法解析和实现步骤。通过本文的解析,读者可以更好地理解和解决Open judge C16H问题中的Magical Balls部分。 ... [详细]
  • 本文介绍了在iOS开发中使用UITextField实现字符限制的方法,包括利用代理方法和使用BNTextField-Limit库的实现策略。通过这些方法,开发者可以方便地限制UITextField的字符个数和输入规则。 ... [详细]
  • 本文详细介绍了使用C#实现Word模版打印的方案。包括添加COM引用、新建Word操作类、开启Word进程、加载模版文件等步骤。通过该方案可以实现C#对Word文档的打印功能。 ... [详细]
  • Ihaveaworkfolderdirectory.我有一个工作文件夹目录。holderDir.glob(*)>holder[ProjectOne, ... [详细]
  • 带添加按钮的GridView,item的删除事件
    先上图片效果;gridView无数据时显示添加按钮,有数据时,第一格显示添加按钮,后面显示数据:布局文件:addr_manage.xml<?xmlve ... [详细]
  • 使用C++编写程序实现增加或删除桌面的右键列表项
    本文介绍了使用C++编写程序实现增加或删除桌面的右键列表项的方法。首先通过操作注册表来实现增加或删除右键列表项的目的,然后使用管理注册表的函数来编写程序。文章详细介绍了使用的五种函数:RegCreateKey、RegSetValueEx、RegOpenKeyEx、RegDeleteKey和RegCloseKey,并给出了增加一项的函数写法。通过本文的方法,可以方便地自定义桌面的右键列表项。 ... [详细]
  • node.jsurlsearchparamsAPI哎哎哎 ... [详细]
  • 如何自行分析定位SAP BSP错误
    The“BSPtag”Imentionedintheblogtitlemeansforexamplethetagchtmlb:configCelleratorbelowwhichi ... [详细]
  • Android JSON基础,音视频开发进阶指南目录
    Array里面的对象数据是有序的,json字符串最外层是方括号的,方括号:[]解析jsonArray代码try{json字符串最外层是 ... [详细]
  • 本文详细介绍了Spring的JdbcTemplate的使用方法,包括执行存储过程、存储函数的call()方法,执行任何SQL语句的execute()方法,单个更新和批量更新的update()和batchUpdate()方法,以及单查和列表查询的query()和queryForXXX()方法。提供了经过测试的API供使用。 ... [详细]
  • 怎么在PHP项目中实现一个HTTP断点续传功能发布时间:2021-01-1916:26:06来源:亿速云阅读:96作者:Le ... [详细]
  • 本文介绍了在处理不规则数据时如何使用Python自动提取文本中的时间日期,包括使用dateutil.parser模块统一日期字符串格式和使用datefinder模块提取日期。同时,还介绍了一段使用正则表达式的代码,可以支持中文日期和一些特殊的时间识别,例如'2012年12月12日'、'3小时前'、'在2012/12/13哈哈'等。 ... [详细]
  • Python爬虫中使用正则表达式的方法和注意事项
    本文介绍了在Python爬虫中使用正则表达式的方法和注意事项。首先解释了爬虫的四个主要步骤,并强调了正则表达式在数据处理中的重要性。然后详细介绍了正则表达式的概念和用法,包括检索、替换和过滤文本的功能。同时提到了re模块是Python内置的用于处理正则表达式的模块,并给出了使用正则表达式时需要注意的特殊字符转义和原始字符串的用法。通过本文的学习,读者可以掌握在Python爬虫中使用正则表达式的技巧和方法。 ... [详细]
author-avatar
daadhkiw_267
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有