[英]How can I reject a string containing non-consecutive characters in a date format
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.
我希望尽可能灵活,因此我决定我的日期格式字符串可以包含 YY 或 YYYY、MM 或 MMM、DD 或 DDD、hh mm 和 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:我已经制定了一些正则表达式 - 例如,匹配以下内容将显示月份是 3 个字符格式:
([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)
区分大小写 - mm 和 MM 不一样(如上)
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.您可以将
\\w
更改为[YMDhms]
以仅检查这六个字母。
Pattern details图案详情
(\\w)
- Group 1 (further referenced to with the \\1
backreference): a word char (\\w)
- 第 1 组(通过\\1
反向引用进一步引用):一个字字符\\1*
- zero or more occurrences of the same char as in Group 1 \\1*
- 与 Group 1 中相同的字符出现零次或多次(?!\\1)
- set a boundary, make sure there next char is not the same as the char in Group 1 (?!\\1)
- 设置边界,确保下一个字符与 Group 1 中的字符不同.*
- any zero or more chars other than line break chars, as many as possible .*
- 除换行符以外的任何零个或多个字符,尽可能多\\1
- the same char as in Group 1. \\1
- 与 Group 1 相同的字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.