Is matching optional in Python regex expression?

I wrote the following regex to match human readable time on the command line:

^(?:(?:(?:(\d+)d\s*)?(\d+)h\s*)?(\d+)m\s*)?(\d+)s$

      

Using non-capturing strings, this regex matches "human-readable" time equally well in the following formats:

1d 2h 3m 4s
1h 2m 3s
1m 2s
1s

      

... and ...

1d2h3m4s
1h2m3s
1m2s
1s

      

In this regex, if I include the value minutes

, I must also include the value seconds

. I cannot just provide 15m

either 1d3m

, I have to provide 15m0s

or 1d0h3m0s

.

Is it possible to extend the regex to match these two use cases? How? Please note: I am not necessarily looking for a dropdown menu solution, but it will be helpful to evaluate the pointer in the right direction.

Update

Just a quick update I made a while ago for a regular expression in Python.

+3


source to share


4 answers


You can use this pattern:

\A(?=\S)(?:\d+d)?(?:\h*\d+h)?(?:\h*\d+m)?(?:\h*\d+s)?\z

      



The approach is to make all elements optional. Looking at the beginning ensures that there is at least a symbol that is not a space. (in other words, it ensures that at least one element is present)

+2


source


Rather, while maintaining this regex and trying to tweak it, I would suggest simplifying your regex significantly:

/ *(\d+)([dhms])/gm

      



Demo version of RegEx

As you can see, this matches all of your current and suggested lines. Then you can handle both captured groups in your code.

+2


source


your seconds files are not optional. Not? after it.so all non-s fields will fail.

See demo.

http://regex101.com/r/iX5xR2/28

I have applied a question mark.

+1


source


You can use nested groups:

/^(?:(?:(?:(\d+)d\s*)?(\d+)h\s*)?(\d+)m\s*)?(\d+)s$/g

      

The value for d

, h

, m

and s

relates to groups 1, 2, 3 and 4 respectively.

Here's a regex demo !

0


source







All Articles