从字符串解析数字

2024-09-30 12:20:45 发布

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

我有一根绳子如下

text1: 123 wwer 123 text2: 456 oirn 456

我在试着分析text1后的数字。我犯了一些我查不出来的错误。在

^{pr2}$

但我的目的是单独分析出123。我犯了什么错误

text1的输出应该是[123123],text2的输出应该是[456456456]


Tags: 目的错误数字绳子text1pr2text2oirn
3条回答

您可以使用以下正则表达式:(text\d+):[^\d]+(\d+)[^\d]+(\d+)

Demo

短解:

text = 'text1: 123 wwer 123 text2: 456 oirn 456'
result = [list(i) for i in re.findall(r'text\d+: (\d+) \w+ (\d+)', text)]
print(result)

输出(消耗对):

^{pr2}$

我把它分成两部分。在

1)将整个字符串拆分为text\d出现的部分。 2) 遍历列表,找到所有的数字。在

>>> import re
>>> st = 'text1: 123 wwer 123 text2: 456 oirn 456'
>>> lst = re.split(r'(text\d)',st)[1:]
>>> {i:re.findall(r'\d+',j) for i,j in zip(lst, lst[1:])[::2]}
{'text2': ['456', '456'], 'text1': ['123', '123']}

相关问题 更多 >

    热门问题