使用正则表达式从字符串向列表中添加数字

2024-09-29 01:33:01 发布

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

简单代码位:

import re

data = "t3st 11.22.3333.44 bl4h"
r=re.compile(r'([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)')
s=r.search(data)
print (s.group())

此时,s.group()=“11.22.3333.44”非常好。
我想列出小数点以内的数字组:

list = ["11","22","3333","44"]

我怎样才能做到这一点?谢谢。你知道吗


Tags: 代码importresearchdatagroup数字list
2条回答

将模式更改为每个号码一组:

import re

data = "t3st 11.22.3333.44 bl4h"
r=re.compile(r'([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)') # individual groups per numbers
s=r.search(data)
print ( list( s.groups()) )  

输出:

['11', '22', '3333', '44']

Match.groups()返回元组,请参见Doku

为什么不简单地在.上分割输出字符串呢?你知道吗

>>> import re

>>> data = "t3st 11.22.3333.44 bl4h"
>>> r=re.compile(r'([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)')
>>> s=r.search(data)
>>> print (s.group().split('.'))
['11', '22', '3333', '44']

相关问题 更多 >