2024-09-30 12:20:45 发布
网友
我有一根绳子如下
text1: 123 wwer 123 text2: 456 oirn 456
我在试着分析text1后的数字。我犯了一些我查不出来的错误。在
但我的目的是单独分析出123。我犯了什么错误
text1的输出应该是[123123],text2的输出应该是[456456456]
您可以使用以下正则表达式:(text\d+):[^\d]+(\d+)[^\d]+(\d+)
(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)
输出(消耗对):
我把它分成两部分。在
1)将整个字符串拆分为text\d出现的部分。 2) 遍历列表,找到所有的数字。在
text\d
>>> 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']}
您可以使用以下正则表达式:
(text\d+):[^\d]+(\d+)[^\d]+(\d+)
Demo
短解:
输出(消耗对):
^{pr2}$我把它分成两部分。在
1)将整个字符串拆分为
text\d
出现的部分。 2) 遍历列表,找到所有的数字。在相关问题 更多 >
编程相关推荐