代码之家  ›  专栏  ›  技术社区  ›  haxtar

将两个规则合并为一个子规则

  •  -1
  • haxtar  · 技术社区  · 6 年前

    我有一堆句子,要么以“这个颜色是红色”开头,要么以“这个颜色是粉色”开头。

    我想创建一个 re.sub() 规则要把两者结合起来删除,并保留“句子的其余部分”。我怎样才能把这两个子规则结合起来呢?:

    a = "This color is red rest of sentence"
    b = "This color is pink rest of sentence"
    
    re.sub('This.+ red','', a)
    re.sub('This.+ pink','', b)
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   pault Tanjin    6 年前

    你可以用 | 作为 OR regex中的操作:

    print(re.sub('This.+ (red|pink)', '', a))
    # rest of sentence
    print(re.sub('This.+ (red|pink)', '', b))
    # rest of sentence