2

I need to build a regex that have the following:

Rules to be applied:

  • exactly 14 characters
  • only letters (latin characters) and numbers
  • at least 3 letters

Regex still confuses me so I am struggling to get the correct output. I want to use it with swift and swiftui in an app I am making

(?=(.*[a-zA-Z]){3,}([0-9]){0,}){14,14}$

I tried this. But I know it is not the way

kikuchan
  • 23
  • 3

2 Answers2

3

I would use a positive lookahead for the length requirement:

^(?=.{14}$)(?:[A-Za-z0-9]*[A-Za-z]){3}[A-Za-z0-9]*$

This pattern says to match:

  • ^ from the start of the input
  • (?=.{14}$) assert exact length of 14
  • (?:
    • [A-Za-z0-9]*[A-Za-z] zero or more alphanumeric followed by one alpha
  • )
  • [A-Za-z0-9]* any alphanumeric zero or more times
  • $ end of the input
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

You need to use

^(?=(?:[0-9]*[a-zA-Z]){3})[a-zA-Z0-9]{14}$

Details

  • ^ - start of string
  • (?=(?:[0-9]*[a-zA-Z]){3}) - at least three repeations of a letter after any zero or more digits sequence required
  • [a-zA-Z0-9]{14} - fourteen letters/digits
  • $ - end of string.

See the regex demo.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • It worked! One question, what does the (?=?: mean in the regex? – kikuchan Dec 20 '22 at 12:37
  • @kikuchan `(?=...)` is a [positive lookahead](https://www.regular-expressions.info/lookaround.html) and the `(?:....)` is a [non-capturing group](https://stackoverflow.com/q/3512471/3832970). – Wiktor Stribiżew Dec 20 '22 at 12:38