python - 模式后面不再有数字正则表达式 python

标签 python regex python-2.7

我有一个包含多个值的列表,例如:

l = [
 '210-4521268-18',
 '210.0622277.13', 
 'rachid 312-0653348-08',
 '3000401732 00000 064 77063',
 ....,
 '312-0653348-08 rachid'
]

我只想获取与以下正则表达式相对应的格式为“210.0622277.13”的项目:

r'\d{3}\D?\d{7}\D?\d{2}'

到目前为止,我已经编写了以下正则表达式来获取这些值:

regex = re.compile(r'((\d{3}\D?\d{7}\D?\d{2}$)|(^\d{3}\D?\d{7}\D?\d{2}))')
# loop through the list to fetch desired part of value
for line in l:
   match = regex.search(line)
   if match:
       print('line : {} found a match {}'.format(line, line[match.start():match.end()]))
   else:
      print('line : {} found no match'.format(line)

问题是值“3000401732 00000 064 77063”被匹配

如何优化此正则表达式,使其不再接受所需模式后的数字,以防模式后有更多数字,该值将被丢弃。

我需要捕捉的比赛是:

l = [
   '210-4521268-18',
   '210.0622277.13', 
   '312-0653348-08',
   '312-0653348-08'
]

所以输出将类似于:

line : 210-4521268-18 found a match 210-4521268-18
line : 210.0622277.13 found a match 210.0622277
line : rachid 312-0653348-08 found a match 312-0653348-08
line : 3000401732 00000 064 77063 found no match
line : 312-0653348-08 rachid found a match 312-0653348-08

最佳答案

这应该适合你:

\d{3}[^\d]\d{7}[^\d]\d{2}

现场演示 here

说明:

\d{3} :查找 3 位数字

[^\d]\d{7}:查找非数字,然后查找 7 位数字

[^\d]\d{2}:再次查找非数字,然后查找 2 位数字

关于python - 模式后面不再有数字正则表达式 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46854846/

相关文章:

regex - Perl 正则表达式将 {a, b, c, ..., x} 转换为 (a|b|c|...|x)

java - 正则表达式匹配空格、数字和 8 个字符

python - 折叠 Python 列表,保留唯一列和最高值

python-2.7 - 如何在 python 2.7 windows 10 中安装 difflib 模块

python - scrapy 过滤重复请求

python sqlAlchemy : got InvalidRequestError after change class location

javascript - 使用 javascript 的正则表达式将多个数字返回到数组中

python-2.7 - 使用循环绘制 n 个图表 Python

python - 在完全平坦的 HTML 层次结构上使用 BeautifulSoup

python - 如何在 python xmlrpc 服务器的 regested 函数中获取请求的 ip 地址