Reputation: 148524
I'm trying to crete a regex which can accept general SQL / Js date such as:
31 feb 2012
I already made a regex :
(0[1-9]|[12]\d|3[01])[ ]+(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)[ ]+[12]\d{3}$
but how can i tell the regex to ignore the appearence order of the items :
so it can accept :
Apr 31 2010
2010 Apr 31
...
...
Upvotes: 0
Views: 78
Reputation: 336108
One solution using lookahead assertions:
var myregexp = /^(?=.*(\b[A-Za-z]{3}\b))(?=.*(\b\d{1,2}\b))(?=.*(\b\d{4}\b))/;
var match = myregexp.exec(subject);
if (match != null) {
month = match[1];
days = match[2];
year = match[3];
}
Explanation:
^ # Start of string
(?= # Look ahead to see if the following can be matched:
.* # Any number of characters
( # followed by (capturing this in group no. 1)
\b # Start of word
[A-Za-z]{3} # Three ASCII letters
\b # End of word
) # End of capturing group no. 1
) # End of lookahead assertion.
(?= # Look ahead to see if the following can be matched:
.* # Any number of characters
( # followed by (capturing this in group no. 1)
\b\d{1,2}\b # a one- or two-digit number
) # etc.
)
(?= # Lookahead no. 3
.*
(
\b\d{4}\b # a four-digit number
)
)
Upvotes: 3
Reputation: 843
You should pool the characters into groups, and then you can use OR to accept them in the different orders in which they occur in your strings. You cannot built a general regex that can work with any order - you have to clearly specify all the orders in which they occur.
Upvotes: 1