使用cod中的另一个正则表达式修改正则表达式

2024-05-05 06:06:52 发布

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

我有一个字符串“out”,我需要在一个名为“text”的文本中将另一个字符串“更改为

out = 'hello $ world'
into = '###'
text = 'this hello \n$ world text'

我还想知道是否有任何变化

在我看来,我应该首先转义“out”text(以允许修改像“$”这样的字符)。然后,我应该将所有ur'\s+'替换为'\s+',结果字符串应该包含要替换为'###'的正则表达式

总而言之,我有这样的文本:

text = 'this hello \n$ world text'

因此,我希望:

result: 'this ### text'

我试过这个:

re.sub(re.sub(ur'\s+', '\s+', re.escape(out)), into, text)

结果是:

'this hello \n$ world text'

还有:

re.sub(re.sub(ur'\s+', ur'\s+', re.escape(out)), into, text)

同样的结果

我认为“\”字符有一些问题,但有点让人困惑,我如何解决它?我正在运行python 2.7


Tags: 字符串text文本rehelloworldresultout
1条回答
网友
1楼 · 发布于 2024-05-05 06:06:52

这里的主要问题是re.escape(..)也漏掉了空格。事实上:

>>> re.escape('hello $ world')
'hello\\ \\$\\ world'

然而,用r'\s+'代替r'\ '很容易改变这一点:

re.sub(r'\\\s+',r'\s+',re.escape(out))

或填写代码:

>>> re.sub(re.sub(ur'\\\s+', ur'\s+', re.escape(out)), into, text)
'this ### text'

由于原始字符串中的两个空格现在映射到同一个“r”\s+'',因此可以通过替换r\(\\\s+)+'来进一步提高结果正则表达式的效率:

>>> re.sub(re.sub(ur'(\\\s+)+', ur'\s+', re.escape(out)), into, text)
'this ### text'

您可以通过简单地比较旧的text和新的`,来检测是否有变化。例如:

new_text = re.sub(re.sub(ur'(\\\s+)+', ur'\s+', re.escape(out)), into, text)
change = text != new_text # change is a bool that is True if there is change

相关问题 更多 >