【问题标题】:Python regex replace numbers < 100 with '100 BLOCK', else replace last two digits with '00 BLOCK'Python 正则表达式将数字 < 100 替换为“100 BLOCK”,否则将最后两位数字替换为“00 BLOCK”
【发布时间】:2019-11-06 18:06:37
【问题描述】:

我正在使用 Python 2.7.13 来清理一些数据。

我有一个数字列表,如果字符串以数字开头。如果起始数字小于100,我需要用'100 BLOCK'替换它。如果数字更大,我需要用'00 BLOCK' 替换最后两位数

保证文本列表以 0 或更大的数字开头。

例子

'1234 foo foo' --> '1200 BLOCK FOO FOO'
'19 bar bar' --> '100 BLOCK bar bar'
'0 baz baz' --> '100 BLOCK baz baz'

目前,我在 for 循环中运行两个不同的正则表达式:

for row in listOfNumbers:
    /* Replace last two digits with '00 BLOCK' */
    firstRegex = re.sub(r'^(\d*)\d{2}\b', r'\g<1>00 BLOCK', row)

    /* Replace digits under 100 with '100 BLOCK'. This includes 0 */
    secondRegex = re.sub(r'^(\d{1,2})\b', '100 BLOCK', firstRegex)

    /* Do other stuff with results

是否有可能在一个正则表达式中以某种方式做到这一点?

【问题讨论】:

    标签: regex python-2.7 list


    【解决方案1】:

    你可以使用

    import re
    strs = ['1234 foo foo', '19 bar bar', '0 baz baz']
    rx = re.compile(r'^(?:(\d{1,2})|(\d+)\d{2})(?!\d)')
    for s in strs:
        print(rx.sub(lambda x: '100' if x.group(1) else x.group(2)+"00", s))
    

    输出:

    1200 foo foo
    100 bar bar
    100 baz baz
    

    Python demo

    正则表达式匹配:

    • ^ - 字符串开头
    • (?:(\d{1,2})|(\d+)\d{2}) - 匹配 2 个备选方案的非捕获组:
      • (\d{1,2}) - 第 1 组:一位或两位数 (
      • | - 或
      • (\d+)\d{2} - 第 2 组捕获一个或多个数字,然后捕获任意 2 个数字
    • (?!\d) - 右边没有数字。

    如果Group 1匹配100用于替换匹配,否则返回Group 2后附00的内容。

    【讨论】:

    • Stribizew 谢谢!我在“块”中添加了它,效果很好。只是好奇,我对 lambda 函数有点熟悉,我想知道 'x' 的值在哪里传递给 lambda 函数?
    • @siushi 见lambda x: ...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-30
    相关资源
    最近更新 更多