【问题标题】:How to replace words while preserving punctuation using regex?如何在使用正则表达式保留标点符号的同时替换单词?
【发布时间】:2023-01-21 02:28:24
【问题描述】:

我的目标是使用正则表达式和 python 库 re 替换所有后跟标点符号的“cat”实例,同时保留标点符号。到目前为止,这是我的方法,也是一个最小的可重现示例:

import re

your_string = "Is this cat sleeping? Sleepy cat? Sleepy cat!"

match = re.findall(r"\bcat[/./?!]", your_string)
new_string = re.sub(r"cat","dog", match)
res_str = re.sub(r"\bcat[/./?!]", new_string, your_string, flags=re.IGNORECASE)

理想的输出应该是:“这只猫在睡觉吗?困狗?困狗!”

编辑:我的尝试没有成功,因为它看起来 re.sub 不能接受字符串列表

【问题讨论】:

  • 你的错误是什么意思?你从来没有告诉我们输出有什么问题。我们绝对不必运行您的代码来解决这个问题。该信息必须包含在您的帖子中。
  • 嗨,Random Davis,谢谢你告诉我。我澄清这只是一个 MRE

标签: python regex python-re


【解决方案1】:

使用环视更改您的正则表达式 >> cat(?=[/./?!])。

这样就可以直接使用sub函数如下。

import re

your_string = "Is this cat sleeping? Sleepy cat? Sleepy cat!"

re.sub(r"cat(?=[/./?!])","dog", your_string)

查看演示 here。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多