XuMuK XuMuK - 5 months ago 9
Python Question

Python regex match numbers or nothing

I have strings:

1st one

\-1,1\N,0.0464128206,0.1106913625,-0.0261445305\


2nd one

\-1,1\N,0.,0.,0.\


It can be done manually to the

\-1,1\N,0.0,0.0,0.0\


but I am trying to make script working without any editing

My RegEx is

\d,\d\\[A-Z],[-]?\d+.\d+,[-]?\d+.\d+,[-]?\d+.\d+


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

UPD:
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.

Answer

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

\d,\d\\[A-Z],[-]?\d+\.\d*,[-]?\d+\.\d*,[-]?\d+\.\d*

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:

\d,\d\\[A-Z](?:,-?\d+\.\d*){3}

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