【问题标题】:Delete numbers not dates in Python (regex)在 Python 中删除数字而不是日期(正则表达式)
【发布时间】:2015-12-10 10:48:41
【问题描述】:

我知道how to delete extra-word numbers in Python,与:

s = re.sub("^\d+\s|\s\d+\s|\s\d+$", " ", s)

我想知道是否可以在保持日期的同时执行相同的操作:

s = "I want to delete numbers like 84 but not dates like 2015"

在英语中,一个快速而肮脏的规则可能是:如果数字以 18、19 或 20 开头并且长度为 4,则不要删除。

【问题讨论】:

    标签: python regex


    【解决方案1】:

    要匹配除以18/19/20 开头的 4 位序列以外的任何数字序列,您可以使用

    r'\b(?!(?:18|19|20)\d{2}\b)\d+\b'
    

    regex demo

    正则表达式匹配:

    • \b - 引导词边界
    • (?!(?:18|19|20)\d{2}\b) - 一个否定的前瞻,它限制后续模式 \d+ 仅在没有 181920 位于开头然后紧跟两位数字 \d{2} 时匹配(注意您可以将前瞻缩短为(?!(?:1[89]|20)\d{2}\b),但很多人通常不赞成这样做,因为可读性会受到影响)
    • \d+ - 1 位或多位数字
    • \b - 词尾边界

    Python code:

    p = re.compile(r'\b(?!(?:18|19|20)\d{2}\b)\d+\b')
    test_str = "Stack Overflow is a privately held website, the flagship site of the Stack Exchange Network, 4 5 6 created in 2008"
    print p.sub("", test_str)
    

    【讨论】:

    • 刚想到浮点值,想出了\b(?!(?:18|19|20)\d{2}\b(?!\.\d))\d*\.?\d+\b
    • 感谢您的快速回复,但使用 Stack Overflow is a privately held website, the flagship site of the Stack Exchange Network, 4 5 6 created in 2008 它只会删除第一个数字 (4),而不是 5 和 6...请参阅:regex101.com/r/tB0qR8/1
    • 关于您的第一条评论,非常感谢您的改进。
    • It works 如果您添加 /g 标志。在 Python 中,re.sub 默认替换所有匹配项(无需指定任何内容)。
    猜你喜欢
    • 2010-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多