Home > Enterprise >  Struggling with RegEx validation and formating for specfici ID format
Struggling with RegEx validation and formating for specfici ID format

Time:08-27

I have couple specific string formatting i want to achieve for different entities:

Entity 1: 1111-abcd-1111 or 1111-abcd-111111

Entity 2: [10 any symbol or letter(all cap) or number]-[3 letters]

Entity 3: [3 letters all cap]-[3 any]-[5 number]

Not sure if Regex is best approach, because i also want to use this as validator when user starts typing the char's it will check against that Entity selected and then against it's RegEx

CodePudding user response:

Here is a regex with some input strings:

const strings = [
  '1111-abcd-1111',     // match
  '1111-abcd-111111',   // match
  '1111-abcd-1111111',  // no match
  'ABCS@!%!3!-ABC',     // match
  'ABCS@!%!3!-ABCD',    // nomatch
  'ABC-@A3-12345',      // match
  'ABC-@A3-1234'        // no match
];
const re = /^([0-9]{4}-[a-z]{4}-[0-9]{4,6}|.{10}-[A-Za-z]{3}|[A-Z]{3}-.{3}-[0-9]{5})$/;
strings.forEach(str => {
  console.log(str   ' => '   re.test(str));
});

Result:

1111-abcd-1111 => true
1111-abcd-111111 => true
1111-abcd-1111111 => false
ABCS@!%!3!-ABC => true
ABCS@!%!3!-ABCD => false
ABC-@A3-12345 => true
ABC-@A3-1234 => false

Explanation of regex:

  • ^ - anchor text at beginning, e.g. what follows must be at the beginning of the string
  • ( - group start
  • [0-9]{4}-[a-z]{4}-[0-9]{4,6} - 4 digits, -, 4 lowercase letters, -, 4-6 digits
  • | - logical OR
  • .{10}-[A-Za-z]{3} - any 10 chars, -, 3 letters
  • | - logical OR
  • [A-Z]{3}-.{3}-[0-9]{5} - 3 uppercase letters, -, any 3 chars, -, 5 digits
  • ) - group end
  • $ - anchor at end of string

Your definition is not clear; you can tweak the regex as needed.

  • Related