-1

I created a regex to parse two floating point numbers and a * symbol between them using Python. As I am completely new to both I've tried basic online guides on using re library and regex itself. I came up with ((\d+)?(\.?)\d+)\*((\d+)?(\.?)\d+) which works fine here even for the string in question, 2+21.0*2*2.

But if I use this expression and string in Python like so m = re.match(r"((\d+)?(\.?)\d+)\*((\d+)?(\.?)\d+)", "2+21.0*2*2") it gives me "None" object. I do not see any obvious problems, any ideas why it does not work?

keycattie
  • 1
  • 1

2 Answers2

0

regex101.com finds the match 21.0*2 in the string 2+21.0*2*2. re.match doesn't because match always has to include the start of the string. Using re.search instead works.

Alex Hall
  • 34,833
  • 5
  • 57
  • 89
0

As docs says regarding re.match:

If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding match object. Return None if the string does not match the pattern

regex101 show that there is match starting at first digit of 21. You should use re.search instead:

import re
m = re.search(r"((\d+)?(\.?)\d+)\*((\d+)?(\.?)\d+)", "2+21.0*2*2")
print(m is None)  # False
Daweo
  • 31,313
  • 3
  • 12
  • 25