如何在一个替换字符串中写入一个数字,该字符串的组的格式是\n没有空格?

2024-10-03 23:21:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个正则表达式对象和日期格式化程序的替换代码

简化代码如下:

assembledString = myRegex.sub(r"\2\3\4\5\6", textToChange)
#Where \2 , \3 ,\4 etc. are the groups of my regular expression object. 

所以assembledString由放在一起的组组成,但是我想在组“\3”和“\4”之间插入数字“0”。但是,当我这样做时,它被读取为'\30',即组30。类似地,当我在替换字符串中保留空格时,例如r“\2\3 0\4\5\6”,空格也被插入assembledString

我尝试过连接替换字符串以及使用转义字符和引号,但没有找到解决方案

非常感谢


Tags: ofthe对象字符串代码程序myetc
2条回答

它通常不应该这样解释,但是如果您已经尝试了所有其他方法,并且为运行添加一点时间不是问题,那么请尝试分两步执行

首先,您不仅添加了“0”,而且还添加了一些在其他任何地方都找不到的奇怪单词,接下来,您只将该单词替换为null“”

## r"\2\3WEIRD0\4\5\6"
then use [WEIRD] in regex and delete it from assembled_string.

您可以使用\g<number of group>doc)。从文件:

... \g uses the corresponding group number; \g<2> is therefore equivalent to \2, but isn’t 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.

import re

s = 'This will insert 0 between AB'

print( re.sub(r'([A-Z])([A-Z])', r'\g<1>0\g<2>', s) )

印刷品:

This will insert 0 between A0B

相关问题 更多 >