用于打印数字的特定实例的正则表达式模式

2024-10-06 13:22:42 发布

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

下面是我的代码,我只想得到值265,我不想要255 MT和233

import re 
string1 = "start news, having 255 MT, 233 and 265"
price_find = re.findall(r'^\d{3}\s[A-Z]{2}|\d{3}', string1)
print(price_find)

如果我运行这个,我会得到255和265

['255', '233', '265']

但我试图得到如下输出:

['233', '265']

Tags: and代码importrefindstartpricenews
2条回答

只需使用以下正则表达式:

price_find = re.findall(r'\d{3}(?!\sMT)', string1)

它看起来不像是一个正则表达式问题。收集所有数字并使用索引:

import re 
string1 = "start news, having 255 MT, 233 and 265"
price_find = re.findall(r'\d+', string1)
print(price_find[0])  # first,  255
print(price_find[-1]) # last,   265
print(price_find[1])  # second, 233

Python proof

相关问题 更多 >