javascript - How to combine regular expressions -


I have the following functions that validate date formats in two main formats: without and without separators

  function check_date_format (my_date) {var regex = / ^ (\ d {1,2}) (\ / | -) (\ d {1,2}) (\ / | - ) (\ D {2}) $ /; // Regex announcement for date with separator var date_array = my_date.match (regex); If (date_array == null) {regex = / ^ (\ d {2}) (\ d {2}) (\ d {2}) $ /; // Announce regex for date without divider date_array = my_date.match (regex); If (date_array == faucet) {return false; } And {return true; True} true; }  

first .match (regex) An array of 5 elemnts for returns: days (1 or 2 digits), the first separator (- or /), Months (1 or 2 digits), second separator (- or / may be different from first separator) and year (2 digits).

Second .match (regex) Returns for 3 elements (2 digits), Month (2 digits) and Year (2 digits).

I tried to merge the two with this regede:

  / ^ (\ d {1,2}) (\ / | -) (\ d {1,2}) (\ / | -) (\ d {2}) $ | ^ (\ D {2}) (\ D {2}) (\ d {2}) $ /  

and verification works but my_date 8 An array of cells is formed where the first 5 or the last 3 will be undefined on the basis of which the part of the regeses corresponds to the pattern.

Is there a way to merge the two parts and return an array with only 5 or 3 cells, on which basis was matched?

Here are several date formats and one for merging and division regexes testing.

After

this should regex what you want:

  / ^ (\ D {1,2}) ([\ / -]?) (\ D {1,2}) \ 2 (\ d {2}) $ /  

Day, Months, respectively, are occupying Group 1, 3, 4.

I use the backreference to ensure that the second separator (between the year and the month) is the same as the same separator, 2 ([\ / -]?) . Therefore, it is slightly different from your code: This mixed separator like " 12 / 3-01 .


Comments