XuMuK XuMuK - 8 months ago 24
Python Question

Python regex match numbers or nothing

I have strings:

1st one


2nd one


It can be done manually to the


but I am trying to make script working without any editing

My RegEx is


How to make RegEx work on \d+ or just skip it if is not present?

I want to make RegEx which will get true for both strings. How to make this part '\d+.\d+' to skip second \d+ if it is absent?
[\d+]? is not working.


Change the part after the . from \d+ to \d*, like this:


The interpretation of \d+\.\d* being:

at least one digit then exactly one dot then zero or one or several digits

Note that I also changed your . to \. (. meaning any character).

Link to debuggex: https://www.debuggex.com/r/nSKH3lbNr8opO09o

-- Update

Your regex could be simplified a bit to this:


It simply factorizes your ,\d+\.\d* knowing that this group is repeated three times. It also changes [-] to - which is cleaner.

The (?: ... ){3} syntax meaning a non-capturing group repeated three times.

Link to the updated debuggex: https://www.debuggex.com/r/Cni47UR71BCgpa2A