I wrote a regular expression for a leetcode problem and I am having issues with it.
when I put the expression into regex101 all of the matches are correct except it won’t match any singular digits such as the 2. when I change the \d+ at the end of it to \d* it accepts the 2, but it then accepts the 1e that I am trying to avoid. What is wrong here?
here is the regular expression:
^([\+-]{0,1}\d+[eE]{0,1}[\+-]{0,1}\d+)$
here is the text I am trying to match:
"2"
"0089"
"2e10"
"-90E3"
"3e+7"
"+6e-1"
here is the text I am trying to avoid matching:
"abc"
"1a"
"1e"
"e3"
"--6"
"-+3"
"95a54e53"
>Solution :
You have two d+s, which means that you aren’t able to match a string like "2". You need to make the ability to specify the [eE][\+-]... part optional using the ? operator:
pattern = re.compile("^([\+-]{0,1}\d+([eE][\+-]?\d+)?)$")