python正则表达式到组数

2024-03-29 00:16:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从这种字符串中提取数字:

"30098.904999  5  ABC                    Da   d 8 06 01 20 00 80 11 C0 04"

首先,我删除所有空白:

test = ' '.join(test.split())

然后我尝试应用以下模式:

pattern  = r"(\d+.\d+) (\d+) ABC Da d 8 (\d\d) (\d\d) (\d\d) (\d\d) (\d\d) (\d\d) (\d\d) (\d\d)"

但是,仍然没有得到任何结果:

    result = re.search(pattern, s)
    print ("result: " + str(result.groups(0)))

  print ("result: " + str(result.groups(0)))
AttributeError: 'NoneType' object has no attribute 'groups'

如果我把第一个号码改为50.309951,那么它就行了。 第一个数字是一个时间戳,其中的数字数量可能会有所不同

欢迎任何帮助!:) 线等回答 j


Tags: 字符串test模式数字result空白dapattern
3条回答

这是因为C0\d\d不匹配。您可以对该部分使用\d\w。但作为一种更通用的方法,您可以使用re.findall()来捕获所有数字:

In [24]: test = "30098.904999  5  ABC                    Da   d 8 06 01 20 00 80 11 C0 04"

In [27]: re.findall(r'\d+(?:\.\d+)?', test)
Out[27]: ['30098.904999', '5', '8', '06', '01', '20', '00', '80', '11', '0', '04']
# If you want C0 too:
In [28]: re.findall(r'\w?\d+(?:\.\d+)?', test)
Out[28]: ['30098.904999', '5', '8', '06', '01', '20', '00', '80', '11', 'C0', '04']

为什么不在删除空格字符后拆分字符串呢

test = ' '.join(test.split())

像这样

您将收到一组项目

['30098.904999', '5', 'ABC', 'Da', 'd', '8', '06', '01', '20', '00', '80', '11', 'C0', '04']
  1. 您不需要使用split,因为您可以使用\s+来匹配一个或多个空格
  2. 你的正则表达式也需要修正

您可以使用以下选项:

(\d+\.\d+)\s+(\d+)\s+ABC\s+Da\s+d\s+8\s+(\d{2})\s+(\d{2})\s+(\d{2})\s+(\d{2})\s+(\d{2})\s+(\d{2})\s+([A-Z]\d)\s+(\d{2})

RegEx Demo

相关问题 更多 >