如何在文本中找到 x 位数字? [英] How to find an x-digit number in a text?

查看:77
本文介绍了如何在文本中找到 x 位数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有更好(更有效)的方法来查找文本中的 x 位数字(数字由 x 位组成)?

Is there a better (more efficient) way to find x-digit number (number consisted of x digits) in a text?

我的方式:

for n in range(0,len(text)):
    if  isinstance(text[n:n+x], (int)) and isinstance(text[n:n+x+1] is False:
        result = text[n:n+x]

return result

编辑 2:

for n in range(0,len(text)):
    try:  
       int(text[n:n+x])
       result = text[n:n+x]
    except:
       pass

return result

推荐答案

import re                                             
string = "hello 123 world 5678 897 word"              
number_length = 3                                     
pattern= r"\D(\d{%d})\D" % number_length   # \D to avoid matching 567           
print re.findall(pattern, string)

输出

["123","897"]

这篇关于如何在文本中找到 x 位数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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