如何正则表达式字符串中长度为 7 的数字但该数字在 Python 中不是以 0 开头? [英] How regex a number length 7 in a string but the number is not start with 0 in Python?

查看:81
本文介绍了如何正则表达式字符串中长度为 7 的数字但该数字在 Python 中不是以 0 开头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的字符串:

I have a string like this:

s = "Abc 3456789 cbd 0045678 def 12345663333"
print(re.findall(r"(?<!\d)\d{7}(?!\d)", s))

Ouput is : 3456789  and 0045678

但我只想得到 3456789.我该怎么做?

but I only want to get 3456789. How can I do that?

推荐答案

根据查找不以 0 开头的 7 位数字的标题,您可以使用:

As per title of finding 7 digit numbers that don't start with 0 you may use:

(?<!\d)[1-9]\d{6}(?!\d)

在匹配开始时注意[1-9],然后匹配接下来的6位数字,使其总共7位.

Note [1-9] at start of match before matching next 6 digits to make it total 7 digits.

RegEx 演示

要匹配任何不以 0 开头的数字,请使用:

To make it match any number that doesn't start with 0 use:

(?<!\d)[1-9]\d*(?!\d)

这篇关于如何正则表达式字符串中长度为 7 的数字但该数字在 Python 中不是以 0 开头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆