【问题标题】:Python - re.sub return pattern rather than replacingPython - re.sub 返回模式而不是替换
【发布时间】:2020-08-03 05:19:23
【问题描述】:

我正在尝试修改 Python 3 中的字典键列表,以便它们可以通过字典中的第一组数字来识别,但它似乎返回的是正则表达式模式而不是数字集。

>>>> import re
>>>>re.sub(r'GraphImages_[0-9]{2}_edge_media_to_caption_edges_0_node_text', '(?<=GraphImages_)\n{3}', 'GraphImages_99_edge_media_to_caption_edges_0_node_text')
'(?<=GraphImages_)\n{3}'
>>>>re.sub(r'GraphImages_[0-9]{2}_edge_media_to_caption_edges_0_node_text', '(?<=GraphImages_)\n{3}', 'GraphImages_123_edge_media_to_caption_edges_0_node_text')
'(?<=GraphImages_)\n{3}'

当上述输出的预期输出分别为99123 时。

任何指导将不胜感激。我不太擅长re

【问题讨论】:

    标签: python-3.x regex


    【解决方案1】:

    如果你只是想提取数字,你需要找到它们,而不是替换:

    re.findall("GraphImages_([0-9]{2,})", yourstring)[0]
    #'99'
    

    事实上,在您的情况下,拆分可能是更好的选择:

    yourstring.split("_")[1]
    #'99'
    

    【讨论】:

      【解决方案2】:

      在下面找到了一个麻烦的解决方法

      try_1 = re.sub('[^0-9]', "", 'GraphImages_99_edge_media_to_caption_edges_0_node_text')
      try_2 = re.sub( '0$', "" , try_1)
      

      【讨论】:

        【解决方案3】:

        你可以使用

        ^\D+(\d+).+
        

        查看demo on regex101.com.

        【讨论】:

        • 感谢您的建议!我得到以下好奇的回溯。 error: bad escape \D at position 1 这导致额外的/ 无济于事
        • 这就是说我不认为这是你或我的正则表达式的问题,但我对re.sub缺乏了解
        猜你喜欢
        • 2016-10-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多