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
  • 4,126
  • 12
  • 42
  • 71
  • 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
  • 42,290
  • 8
  • 54
  • 79