Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

python - regex pattern to print particular instance of a number

Below is my code which i am trying to get only the value 265 and I don't want 255 MT and 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)

If i run this i'm getting both 255 and 265

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

But im trying to get the output as below:

['233', '265']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It does not look like a regex issue. Collect all the numbers and use indexing:

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

See Python proof.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...