3

Possible Duplicate:
Python regular expressions - how to capture multiple groups from a wildcard expression?


I cannot access the group for 3rd or 5th element in the following regex:

>>> x = 'f 167 2958 335 3103 0'
>>> re.search('.(\s\d+){5}', x).group()
'f 167 2958 335 3103 0'
>>> re.search('.(\s\d+){5}', x).group(1)
' 0'
>>> # how do i access no 2958 and 3103

I know I can achieve the above with pattern = '.\s\d+\s(\d+)\s\d+\s(\d+)\s\d+', but thats lame.

Thanks, Amit

Community
  • 1
  • 1
amulllb
  • 3,036
  • 7
  • 50
  • 87

2 Answers2

3

You can use re.findall for this.

result = re.findall('\s\d+', x)

print result[1]  # 2958
print result[3]  # 3103
BrtH
  • 2,610
  • 16
  • 27
0

if this is a general question then findall is your best bet.

If this is the actual thing you are trying to do, split would make more sense:

>>> x = 'f 167 2958 335 3103 0'
>>> l = x.split()
>>> l[2]
'2958'
>>> l[4]
'3103'
Phil Cooper
  • 5,747
  • 1
  • 25
  • 41