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
CodePudding user response:
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
CodePudding user response:
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.