简体   繁体   中英

python regular expression, extracting set of numbers from a string

How can i get the number 24 and 200 from the string "Size:24 Resp_code:200"

by using re in python?, i have tried with \\d+ but then i only get 24 in addition i have also tried this out:

import re

string2 = "  Size:24 Resp_code:200"

regx = "(\d+) Resp_code:(\d+)"

print re.search(regx, string2).group(0)
print re.search(regx, string2).group(1)

here the out put is:

24 Resp_code:200 
24 

any advice on how to solve this ?

thanks in advance

The group 0 contains the whole matched string. Extract group 1, group 2 instead.

>>> string2 = "  Size:24 Resp_code:200"
>>> regx = r"(\d+) Resp_code:(\d+)"
>>> match = re.search(regx, string2)
>>> match.group(1), match.group(2)
('24', '200')
>>> match.groups()  # to get all groups from 1 to however many groups
('24', '200')

or using re.findall :

>>> re.findall(r'\d+', string2)
['24', '200']

Use:

print re.search(regx, string2).group(1) // 24
print re.search(regx, string2).group(2) // 200

group(0) prints whole string matched by your regex. Where group(1) is first match and group(2) is second match.

Check the doc :

If there is a single argument, the result is a single string; if there are multiple arguments, the result is a tuple with one item per argument. Without arguments, group1 defaults to zero (the whole match is returned)

You are doing it right but groups don't start at 0, but 1, group(0) will print the whole match:

>>> re.search(regx, string2).group(1,2)
('24', '200')

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