与 sub() 操作一起使用时,反向引用指的是哪个组? [英] what group does backreference refers to when used with sub() operation?

查看:65
本文介绍了与 sub() 操作一起使用时,反向引用指的是哪个组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码:

<预><代码>>>>text = "想象一个新的*世界*,一个*魔法*的世界">>>模式 = re.compile(r'\*(.*?)\*')>>>pattern.sub(r"\1<\b>", 文本)

输出:

想象一个新的世界<\x08>,一个<\b>魔法<\x08>世界

我有两个问题,

1.) 我不明白为什么反向引用 '\1' 会改变文本的 magic 部分?我读过 '\1' 指的是捕获的第一组.

2.) 为什么 <\b> 输出 <\x08> 即使在使用 'r' 作为前缀之后.我不会遇到 '\n'.

解决方案

我去了 IRC,那里的人告诉我,每次使用重复的匹配字符串捕获组时,都会覆盖 bacreference.

The following code:

>>> text = "imagine a new *world*, a *magic* world"
>>> pattern = re.compile(r'\*(.*?)\*')
>>> pattern.sub(r"<b>\1<\b>", text)

outputs:

imagine a new <b>world<\x08>, a <\b>magic<\x08> world

I have two problems here,

1.) I don't understand why does back reference '\1' changes the magic part of the text? I have read that '\1' refers to the first group which is captured.

2.) Why does <\b> outputs <\x08> even after using 'r' as prefix. I dosen't happen with '\n'.

解决方案

I went to IRC and people there told me that every time a group is captured with repeated match string, the bacreference is overwritten.

这篇关于与 sub() 操作一起使用时,反向引用指的是哪个组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆