Matching two patterns in one python regex, capturing only non-empty values

After many searches and reading, I'm not quite sure what I'm trying to do, this is possible in one step. I want it to fit this:

(\d{1,4})/(\d{1,2})/(\d{1,2}) 2011/12/13 

or

 (\d{1,2})/(\d{1,4})/(\d{1,2}) 12/2011/13 

or

 (\d{1,2})/(\d{1,4})/(\d{1,2}) 12/13/2011 

in one regular expression and fix the values ​​in parentheses.


So what I did was wrap these three without capturing the or statements:

 ^(?:(\d{1,4})/(\d{1,2})/(\d{1,2}))|(?:(\d{1,2})/(\d{1,4})/(\d{1,2}))|(?:(\d{1,2})/(\d{1,2})/(\d{1,4}))$ 

The only problem is to use it on this

 2011/12/13 

what i get:

 2100 10 10 Empty Empty Empty Empty Empty Empty 

I do not like blank pictures. Can I set them so that only non-variable strings are returned ?!

I can come up with many workarounds to do this work, starting with the first matching the correct pattern and then matching the correct captures, checking the captured values ​​for more than an empty string, but it seems to me to be possible in the most regular expression.

Any help is greatly appreciated.

Thanks:)

+4
source share
2 answers

What about:

 ^(?:(?=\d{1,4}/\d{1,2}/\d{1,2})|(?=\d{1,2}/\d{1,4}/\d{1,2})|(?=\d{1,2}/\d{1,2}/\d{1,4}))(\d+)/(\d+)/(\d+)$ 

3 look ahead, make sure you have a date in any of the three formats, then write down 3 date elements.

Explanation:

 ^ : begining of the string (?: : begin non capture group (?=\d{1,4}/\d{1,2}/\d{1,2}) : assume the format is yyyy/mm/dd | : or (?=\d{1,2}/\d{1,4}/\d{1,2}) : format dd/yyyy/mm | : or (?=\d{1,2}/\d{1,2}/\d{1,4}) : format dd/mm/yyyy ) : end of non capture group (\d+)/(\d+)/(\d+) : capture the 3 elements $ : end of string 
+5
source

Here is my punch (short and sweet):

 (\d{2,4})(?=/)/(\d{2,4})(?=/)/(\d{2,4})$ 
+1
source

Source: https://habr.com/ru/post/1386123/


All Articles