【问题标题】:Regex modification in pythonpython中的正则表达式修改
【发布时间】:2017-12-20 16:50:37
【问题描述】:

我正在使用以下正则表达式模式来识别缩写。

mytext = "This is AVGs and (NMN) and most importantly GFD"
mytext= re.sub(r"\b[A-Z\.]{2,}s?\b", "_ABB", mytext)
print(mytext)

我得到如下输出。

This is _ABB and (_ABB) and most importantly _ABB

但是,我想得到输出;

This is AVGs_ABB and (NMN_ABB) and most importantly GFD_ABB

请告诉我我哪里做错了。

【问题讨论】:

    标签: python regex python-3.x


    【解决方案1】:

    使用捕获组来捕获您要匹配的单词边界之间的模式,然后在替换中使用它。第一个捕获组将以\\1 的形式提供。

    mytext = "This is AVGs and (NMN) and most importantly GFD"
    mytext= re.sub(r"\b([A-Z\.]{2,}s?)\b", "\\1_ABB", mytext)
    print(mytext)
    

    Demo of code snippet

    【讨论】:

    • 当然,我会的:)
    • 有没有更好的方法来做到这一点,因为我的真实数据集出现错误error: invalid group reference 1
    • 您似乎有不匹配的文本。在这种情况下,您希望发生什么?
    • @TimBiegeleisen 我认为这不是正则表达式的问题,因为这 mytext= re.sub(r"\b[A-Z\.]{2,}s?\b", "", mytext) 工作正常。但是,\\1_ABB 会发生错误。请让我知道是否有解决此问题的替代方法:)
    • 试试 Wiktor 的答案,它可能马上对你有用。
    【解决方案2】:

    试试这个,

    In [1]: str = "This is AVGs and (NMN) and most importantly GFD"
    In [2]: regex = "[A-Z]{2,}"
    In [3]: import re
    In [4]: result = re.sub(regex, "_ABB", str)
    In [5]: result
    Out[5]: 'This is _ABBs and (_ABB) and most importantly _ABB'
    

    【讨论】:

      【解决方案3】:

      在替换时使用排除,如下所示:

      import re 
      mytext = "This is AVGs and (NMN) and most importantly GFD"
      mytext= re.sub(r"([A-Z]{2,})", "\\1_ABB", mytext)
      print(mytext)
      

      输出:

      This is AVGs_ABB and (NMN_ABB) and most importantly GFD_ABB

      【讨论】:

        【解决方案4】:

        你不需要在这里使用任何捕获组,因为你想用整个匹配替换,它本身就是第 0 组。只需在替换模式中使用\g<0>,请参阅Python re docs

        后向引用 \g<0> 替换了 RE 匹配的整个子字符串。

        查看online Python demo

        import re
        mytext = "This is AVGs and (NMN) and most importantly GFD"
        mytext= re.sub(r"\b[A-Z.]{2,}s?\b", r"\g<0>_ABB", mytext)
        print(mytext)
        # => This is AVGs_ABB and (NMN_ABB) and most importantly GFD_ABB
        

        替换现在是r"\g&lt;0&gt;_ABB",它将每个不重叠的匹配替换为找到的匹配并将_ABB附加到它。

        查看regex demo

        另请注意,在字符类中,. 被解析为常规的 . 符号,而不是匹配任何字符但换行符的“通配符”。

        【讨论】:

        • 非常感谢您的精彩回答 :)
        猜你喜欢
        • 2013-02-07
        • 2014-04-14
        • 1970-01-01
        • 1970-01-01
        • 2022-11-19
        • 1970-01-01
        相关资源
        最近更新 更多