I want to create a regular expression which should satisfy below requirement.
- a-z and A-Z allowed.
- 0-9 allowed.
- no special chars, no space.
- no 2 repeating chars allowed.
- length should be between 6-9 length.
here are some example
abcdef - allowed
abc456 - allowed
Abc685 - allowed
aabc123 - not allowed because 2 aa
sdf112 - not allowed because 2 11
aerwet2345 - not allowed because length > 9
^(?:([a-zA-Z0-9])(?!.\1))$
I have tried this regular expression but seems like repeating 2 chars not working.
CodePudding user response:
Try this:
\b(?:([a-zA-Z0-9])(?!\1)){6,9}\b
Using [a-zA-Z0-9]
already makes sure, special characters are not included, so you won't need .
in the negative lookahead. Also, using {6,9}
on the non capturing group (?:)
limits the results to those with 6, 7, 8 or 9 characters.
If your 'word' starts at the beginning of each line and nothing follows your 'words' on each line, you can/should use ^
and $
instead of the word boundaries \b
, as you did in your example.
CodePudding user response:
Your pattern ^(?:([a-zA-Z0-9])(?!.\1))$
only matches a single character with ([a-zA-Z0-9])
so the assertion as no purpose.
The assertion (?!.\1)
checks that the single captured value is not directly followed by any char except a newline and a backreference to group 1, and as the .\1
matches a single char before the backreference it does not guarantee 2 of the same repeating chars
You could assert not 2 of the same chars from the character class, and then match 6-9 chars.
^(?![a-zA-Z0-9]*([a-zA-Z0-9])\1)[a-zA-Z0-9]{6,9}$