Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

My Regular Expression isn't picking up single digits

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"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+)?)$")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading