【问题标题】:python regex - removing 'word' while keeping ['word']python regex - 在保留 ['word'] 的同时删除'word'
【发布时间】:2018-12-18 07:17:15
【问题描述】:

我想删除Opportunity,同时保留“[机会]”。

Winery Tailspin Electonic Opportunity   [Opportunity].[Opportunity Name]

我该怎么做?

【问题讨论】:

标签: python regex


【解决方案1】:

如果它总是出现在你的“[word]”之前,你可以在 re.sub 中使用 count 参数,如下所示。

    re.sub('Opportunity','',string,count = 1)

【讨论】:

    【解决方案2】:

    我不确定你想要什么 [Opportunity Name] 位,但以下行将删除所有不相邻 [ or ] 的 Opportunity:

    re.sub('([^\[])(Opportunity)([^\]])','\g<1>\g<3>',string)

    此代码在正则表达式中使用分组并以以下形式匹配字符串 (任何不同于 [)(Opportunity)(任何不同于 ] 的字符) 然后替换为第一组和第三组,即相邻字符。 使用您的示例将生效

    Winery Tailspin Electonic [Opportunity].[Opportunity Name]

    但请注意,当且仅当 Opportunity 不是第一个也不是最后一个词时,此解决方案才有效。你的情况是这样吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多