gpt4 book ai didi

python - 当且仅当它在输入字符串中找到枚举时,如何创建删除等于子字符串的元素的正则表达式模式?

转载 作者:行者123 更新时间:2023-12-02 01:31:06 26 4
gpt4 key购买 nike

我在创建正则表达式时遇到了一些问题,如果它接收到带有枚举的字符串( 元素、元素、元素、element_diferent、...和元素)然后只留下 hyjk11l

以外的枚举元素

示例 1:

输入字符串:

"I come with hyjk11l, Mary Johnson, hyjk11l, hyjk11l, hyjk11l and hyjk11l to the center, maybe we'll buy something there"

我需要的输出:

"I come with Mary Johnson to the center, maybe we'll buy something there"

示例 2:

输入字符串:

"In afternoon, I show hyjk11l, John, hyjk11l, and hyjk11l in the lab"

我需要的输出:

"In afternoon, I show with John in the lab"

示例 3:

输入字符串:

"I meet with Katy Perry and hyjk11l here"

我需要的输出:

"I meet with Katy Perry here"

我已经尝试使用 replace() 函数和一些正则表达式组合,但我没有得到想要的结果。我想也许我可以用 replace() 和所有 ", hyjk11l", "hyjk11l", ", and hyjk11l 删除" and/or "and hyjk11l",但是我觉得这很复杂,因为我不知道我得做多少次(这个求通用,就是你不知道将传递给您的输入字符串是什么,因为正则表达式将是)。

最佳答案

以下是您可以执行的操作:

inputs = ["I come with hyjk11l, Mary Johnson, hyjk11l, hyjk11l, hyjk11l and hyjk11l to the center, maybe we'll buy something there",
"In afternoon, I show hyjk11l, John, hyjk11l, and hyjk11l in the lab",
"I meet with Katy Perry and hyjk11l here",
"I meet him and hyjk11l and her there"
]

pat = r"((?:[\s+\,]|\s?and)\s?hyjk11l(?:[\s\,]?)(?=\s))"
for inp in inputs:
tmp = re.sub(pat, "", inp)
print(tmp)

输出:

I come with Mary Johnson to the center, maybe we'll buy something there
In afternoon, I show John in the lab
I meet with Katy Perry here
I meet him and her there

检查 Regex101 处的正则表达式.

解释模式:

  • (?:[\s+\,]|\s?and) :非捕获组,匹配一个或多个空格或逗号 OR 0 或 1 个空格和 and
  • \s? : 0 或 1 个空格
  • hyjk11l : 匹配这个词
  • (?:[\s\,]?) :非捕获组,匹配0或1个空格或逗号
  • (?=\s) :匹配后跟一个空格
  • 整个模式构建一组,将替换为""

关于python - 当且仅当它在输入字符串中找到枚举时,如何创建删除等于子字符串的元素的正则表达式模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73266225/

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