shade917
shade917

Reputation: 105

Regex Reject Consecutive Characters

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

Upvotes: 5

Views: 3608

Answers (1)

Felix Loether
Felix Loether

Reputation: 6190

>>> 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' ]

Upvotes: 4

Related Questions