简体   繁体   中英

Regular expression: to find limited iterations

I need to find numbers in the given string and I need to extract first two numbers from the string. Ex., In second example I need to take 1536 and 678 but this code show the all the containg number.

import re
pattern = r"(\d{1,})"
match = re.findall(pattern, "123")
if match:
    print (match)
match = re.findall(pattern, "1536+678+ 888")
if match:
    print (match)    
match = re.match(pattern, "abc cde")
if match:
    print ("Match 3")

Take the first two from matched results:

print(match[:2])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM