Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 761
shade917 Avatar asked Oct 08 '22 00:10

shade917


1 Answers

>>> 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' ]
like image 159
Felix Loether Avatar answered Oct 12 '22 10:10

Felix Loether