Home > Software design >  Regex to find even occurrence of a character in a string every time it repeats in a string in JavaSc
Regex to find even occurrence of a character in a string every time it repeats in a string in JavaSc

Time:11-21

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

CodePudding user response:

re = /^(?:([A-Z])\1|[^A-Z]) $/

console.log(re.test('YYMMDD-YYYY-DD'))
console.log(re.test('YY'))
console.log(re.test('YYY'))
console.log(re.test('YYYY'))

/^(?:([A-Z])\1|[^A-Z]) $/ = ( (letter the same letter once again) OR non-letter ) repeat once or more

CodePudding user response:

[ 'YYMMDD-YYYY-DD', 'YYMMDD', 'YYMDD', 'Y', 'YY', 'YYY', 'YYYY' ].forEach(str => {
  let ok = /^(?:([a-zA-Z])\1-?) $/.test(str);
  console.log(str   ' => '   ok);
});

Output:

YYMMDD-YYYY-DD => true
YYMMDD => true
YYMDD => false
Y => false
YY => true
YYY => false
YYYY => true

Explanation of regex:

  • ^ -- anchor at start of string
  • (?: -- non-capture group start
  • ([a-zA-Z]) -- 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
  • Related