-1

I have this string:

field = 1400 x 3524

I want to take these numbers into two seperate variables so I can perform multiplication. This is how I do it:

num1 = re.match("(\d{3,4})(?= x)", field).group(1)
num2 = re.match("(?<=x )(\d{3,4})", field).group(1)

I works with the first number, but the second number comes out as a NoneType.

What am I doing wrong?

milka1117
  • 521
  • 4
  • 8
  • 17

2 Answers2

0

Try this:

>>> import re
>>> a = 'field = 1400 x 3524'
>>> m = re.findall( r'\d+', a )
>>> m
['1400', '3524']
>>> 
lenik
  • 23,228
  • 4
  • 34
  • 43
0

re module documentation states that:

Note that patterns which start with positive lookbehind assertions will not match at the beginning of the string being searched; you will most likely want to use the search() function rather than the match() function

In your case that means you should do:

import re
field = "1400 x 3524"
num2 = re.search("(?<=x )(\d{3,4})", field).group(0)
print(num2) # 3524

Note that here beyond changing match to search I also changed group(1) to group(0)

Daweo
  • 31,313
  • 3
  • 12
  • 25
  • don't overcomplicate things =) – lenik Aug 19 '19 at 09:32
  • It is true about what you say the manual says about positive lookbehind and if we were dong `re.match("(?<=x )(\d{3,4})", "x 3524")`, it would fail, i.e. we would need to do `re.search`. But the problem here was bigger than that in that even without using lookbehind, re.match would have failed because we were looking for the second integer, which was not at the beginning of the string. In other words, `re.match("(?:x )(\d{3,4})", field).group(1)` would have failed also. – Booboo Aug 19 '19 at 09:46