gpt4 book ai didi

python : different regular expressions with different substitutions

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

我有几个不同的正则表达式要在给定文本中匹配和替换。

  • regex1 :如果文本包含单词“Founder”,则将所有文本替换为首席执行官
  • 正则表达式2:如果文本包含9位数字,则将其替换为NUM

我尝试使用组合正则表达式来执行此操作,如下所示:

regex = re.compile(r'((.*)founder(.*)|^[0-9]{4}$')

问题是,在正则表达式上应用替换时,我需要知道哪个组合模式匹配才能使用相应的替换。

如果有人能帮助我实现这个,我将不胜感激!

最佳答案

您可以使用re.sub

例如:

import re

s = """ if the text contains the word founder
123456789 sdfsdfsdf sdfsdf sdfsdfsdf"""

text = re.sub("founder", "CEO", s)
text = re.sub("[0-9]{9}", "NUM", text)

print(text)

输出:

 if the text contains the word CEO
NUM sdfsdfsdf sdfsdf sdfsdfsdf

关于 python : different regular expressions with different substitutions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51152622/

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