I need to build a JavaScript regular expression with the following constraints:
- The input string needs to be at least 6 characters long
- The input string needs to contain at least 1 alphabetical character
- The input string needs to contain at least 1 non-alphabetical character
I’m seriously lacking a lookback feature in JavaScript. The thing I came up with:
((([a-zA-Z][^a-zA-Z])|([^a-zA-Z][a-zA-Z]))....)|
(.(([a-zA-Z][^a-zA-Z])|([^a-zA-Z][a-zA-Z]))...)|
(..(([a-zA-Z][^a-zA-Z])|([^a-zA-Z][a-zA-Z]))..)|
(...(([a-zA-Z][^a-zA-Z])|([^a-zA-Z][a-zA-Z])).)|
(....(([a-zA-Z][^a-zA-Z])|([^a-zA-Z][a-zA-Z])))
This looks pretty long. Is there a better way?
How I came to this:
- Regex for alphabetical character is
[a-zA-Z] - Regex for non-alphabetical character is
[^a-zA-Z] - So I need to look for a
[a-zA-Z][^a-zA-Z]or[^a-zA-Z][a-zA-Z]
so(([a-zA-Z][^a-zA-Z])|([^a-zA-Z][a-zA-Z])). - I need to check for n preceding characters and 6-n succeeding characters.
This means:
^– start of the string(?= ... )– followed by (i.e. an independent submatch; it won’t move the current match position).{6}– six characters (“start of string followed by six characters” implements the “must be at least six characters long” rule).*– 0 or more of any character (except newline – may need to fix this?)[a-zA-Z]– a letter (.*[a-zA-Z]therefore finds any string with a letter anywhere in it (technically it finds the last letter in it))[^a-zA-Z]– a non-letter characterIn summary: Starting from the beginning of the string, we try to match each of the following in turn: