www.zhblog.net

环视匹配的实例程序补充

下面是对上一章环视匹配书面数字程序的补充。


import re





def main():

    s1 = 'The population of 1234567890 is growing'

    pattern = r'(?<=\d)(?=(\d{3})+\b)'

    ns = re.sub(pattern, ',', s1)

    print(ns)



    s2 = 'The population of 1234567890s is growing'

    pattern = re.compile(r'(?<=\d)(?=(\d{3})+(?!\d))')

    ns = re.sub(pattern, ',', s2)

    print(ns)



    ns = re.sub(r'(\d+?)(?=(?:\d{3})+\b)', r'\1,', s1)

    print(ns)



    # 利用","逗号来分割前面的表达式

    # 第一次匹配后:1,234567890 此时的"1,"就不再匹配表达式

    # ......

    ns = re.sub(r'(\d)(?=(\d{3})+\b)', r'\1,', s1)

    print(ns)





if __name__ == '__main__':

    main()


结果:

The population of 1,234,567,890 is growing

The population of 1,234,567,890s is growing

The population of 1,234,567,890 is growing

The population of 1,234,567,890 is growing

展开阅读全文

评论

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 心情