I am still very new to Regex and basically what I need to do is create a rule that accepts numbers and letters but no consecutive characters are allowed to be entered.
For example: abcd --> ok, abbcd --> bad
I have most of it to work but the part I cant figure out is exactly how do I prohibit consecutive characters?
My Code so far:
/^[A-Za-z-0-9]{8,15}$/i
>>> r = /^((\w)(?!\2))+$/i
>>> r.exec('abbcd')
null
>>> r.exec('abcd')
[ 'abcd',
'd',
'd',
index: 0,
input: 'abcd' ]
The \2
part is a back reference and matches whichever character was last matched by the group (\w)
. So the negative lookahead (?!\2)
means "not followed by the character itself." If some terms I used here are unfamiliar to you, you should look them up on MDN's Regular Expression Documentation.
To limit the length of the accepted strings to 8-15 characters as in the OP, change the +
to {8,15}
:
>>> r = /^((\w)(?!\2)){8,15}$/i
>>> r.exec('abcd')
null
>>> r.exec('abcdabcd')
[ 'abcdabcd',
'd',
'd',
index: 0,
input: 'abcdabcd' ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With