Issue
Regex to find even occurrence of a character in a string every time it repeats in a string
Example:
YYMMDD-YYYY-DD true
YYMDD false
Y,M,D are case sensitive Y,M,D can appear multiple time at multiple postion in pairs in string but each pair must be even.
I have applied the above even check using for loop but have to replace for loop with regex I have also tried it with the below regex but it didn’t worked
if (result.match(/M{2,}/) || result.match(/D{2,}/) || result.match(/Y{2,}/)) {}
solution using for loop which i have implemented
Solution
[ 'YYMMDD-YYYY-DD', 'YYMMDD', 'YYMDD', 'Y', 'YY', 'YYY', 'YYYY', 'XX' ].forEach(str => {
let ok = /^(?:([YMD])\1-?)+$/.test(str);
console.log(str + ' => ' + ok);
});
Output:
YYMMDD-YYYY-DD => true
YYMMDD => true
YYMDD => false
Y => false
YY => true
YYY => false
YYYY => true
XX => false
Explanation of regex:
^
-- anchor at start of string(?:
-- non-capture group start([YMD])
-- capture group 1: single alpha character\1
-- repeat capture group 1-?
-- optional-
(if needed change to a character class to allow additional chars))+
-- non-capture group end, repeat 1+ times$
-- anchor at end
Answered By - Peter Thoeny
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.