I'm trying to come up with a regex which will reject non-consecutive characters in a supplied date format. I want to be as flexible as possible, and so I have decided that my date format string can contain YY or YYYY, MM or MMM, DD or DDD, hh mm and ss.
Some of the regex I have worked out already - for example, matching the following will show that the month is a 3 character format:
([M])\\1{2}
I'm totally in the dark with regard to checking that the date format doesn't contain non consecutive characters. For example, the following date formats should be valid:
YYYY-MM-DD hh:mm:ss
hh:mm:ss YYYY-MM-DD
DD/MMM/YYYYhh-mm
But these formats should be rejected
YYYY-MM-DD hh:mm:ss YYYY // year appears twice
hh:mm:ss YYYY-MM-DD hh // hour appears twice
DD/MMM/YYYYhh-mm m // m not consecutive with other m
In the interests of future expansion, I want to allow non consecutive special characters (/ - . : ) etc and reject all non-consecutive alpha-numeric characters. Case sensitive though - mm and MM are not not the same (as above)
Just to be clear - I'm not trying to validate an actual date - I am trying to validate a date format string only.
I suggest checking if there is at least one occurrence of the same character that has already been present before, and then negating the outcome:
function(text) {
return !/(\w)\1*(?!\1).*\1/.test(text);
}
See the regex demo . You may change \\w
to [YMDhms]
to only check these six letters.
Pattern details
(\\w)
- Group 1 (further referenced to with the \\1
backreference): a word char \\1*
- zero or more occurrences of the same char as in Group 1 (?!\\1)
- set a boundary, make sure there next char is not the same as the char in Group 1 .*
- any zero or more chars other than line break chars, as many as possible \\1
- the same char as in Group 1.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.