0
import re

real_comp = re.compile(r'[0-9]*')
real_comp.search('+123i').group()
Out[7]: '' 

I am expecting the the result as "123", but it returns empty. What's wrong?

Lisa
  • 3,588
  • 11
  • 34
  • 66
  • 3
    You are searching for a substring of *zero or more* digits. Your string `+123i` does indeed contain such a substring, of zero length, at the very start. You probably want `+` (one or more) instead of `*` – jasonharper Feb 20 '19 at 18:35

1 Answers1

1

You'll need another quantifier, namely a +:

import re

real_comp = re.compile(r'([0-9]+)')
print(real_comp.search('+123i').group())

Which yields

123

Otherwise the regex engine reports a match before the very first consumed char ( [0-9]* is always true).

Jan
  • 40,932
  • 8
  • 45
  • 77