1

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

2
  • BTW, if you are going to be using a regex on a lot of lines it's a good idea to compile it. Commented Dec 2, 2014 at 12:31
  • BTW, if you are going to be using a regex on a lot of lines it's a good idea to compile it. Commented Dec 2, 2014 at 12:31

3 Answers 3

4

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']
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.