Skip to content
Advertisement

Hard Regex problems: conditionals search if it passes two or all three conditionals

so im having trouble writing regex in javascript. I want to practice using conditionals on regex.

Problem i want to solve:

  • combinations of (small/capital letters) + (numbers) + (special characters)
  • if using two of the possible combinations, the length should be from 10-16 long
  • if using three of the possible combinations, the length should be from 8-16 long

Regex for combinations:

JavaScript

Advertisement

Answer

Interesting problem! You can use an OR pattern: ^((...)|(...)) where you test separately for two or three combinations. Test case:

JavaScript

Result:

JavaScript

Explanation of regex:

  • ^ — anchor at start of string
  • ((..A..)|(..B..)|(..C..)|(..D..)) — logical OR of parts …A… to …D…
  • part …A…:
    • (?=.{10,16}$) — positive lookahead for 10 to 16 chars, AND
    • (?=.*?[a-zA-Z]) — positive lookahead for an upper or lowercase letter, AND
    • (?=.*?[0-9]) — positive lookahead for a number
  • part …B…:
    • (?=.{10,16}$) — positive lookahead for 10 to 16 chars, AND
    • (?=.*?[a-zA-Z]) — positive lookahead for an upper or lowercase letter, AND
    • (?=.*?[W]) — positive lookahead for a special char
  • part …C…:
    • (?=.{10,16}$) — positive lookahead for 10 to 16 chars, AND
    • (?=.*?[0-9]) — positive lookahead for a number, AND
    • (?=.*?[W]) — positive lookahead for a special char
  • part …D…:
    • (?=.{8,16}$) — positive lookahead for 8 to 16 chars, AND
    • (?=.*?[a-zA-Z]) — positive lookahead for an upper or lowercase letter, AND
    • (?=.*?[0-9]) — positive lookahead for a number
    • (?=.*?[W]) — positive lookahead for a special char
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement