gpt4 book ai didi

python - 如何检查两个连续的单词是否具有相同的正则表达式模式

转载 作者:行者123 更新时间:2023-11-28 18:48:34 38 4
gpt4 key购买 nike

我已经尝试了几个小时,但我无法达到我的目标。

这是字符串:'Hello world, By the Way stackoverflow is cool place'。我要查找的是匹配具有相同 Regex 模式的两个连续单词。

例如,我想用字符串 "xx" 替换连续且以大写字母开头的单词。

所以当我将它应用到我的字符串时,结果应该是:

Hello world,xx xx xx stackoverflow 很酷

这是我的代码片段:

myString='Hello world,By The Way stackoverflow is cool place'
re.sub(r"[A-Z]\w+","xx",myString)

但我得到的是:'xx world,xx xx xx stackoverflow is cool place'

最佳答案

使用regex模块:

>>> import regex
>>> text = 'Hello world,By The Way stackoverflow is cool place'
>>> regex.sub(r'\b[A-Z]\w+(?=\s+[A-Z]\w+)|(?<=\b[A-Z]\w+\s+)[A-Z]\w+', 'xx', text)
'Hello world,xx xx xx stackoverflow is cool place'

关于python - 如何检查两个连续的单词是否具有相同的正则表达式模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16481617/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com