0

I need a regular expression to avoid having the same character(@ is the character) twice consecutively but can have them at muliple places. For example:

someword@someword is ok
someword@@someword is not ok
someword@someword@someword is ok too.

So basically this is my existing regular expression /^([a-zA-Z0-9'\-\x80-\xff\*\+ ]+),([a-zA-Z0-9'\-\x80-\xff\*\+\@ ]+)$/ where the first group is the last name and second group is the first name. I have introduced a magical character @ in the first name group which I will replace with a space when saving. The problem is I cannot have consecutive @ symbols.

HamZa
  • 14,051
  • 11
  • 52
  • 72

4 Answers4

6

Looks for any repeated characters (repeated once):

/(.)\1/.test(string) // returns true if repeated characters are found

Looks for a repeated @:

string.indexOf('@@') !== -1 // returns true if @@ is found
Reeno
  • 5,614
  • 10
  • 37
  • 49
3
str.replace(/(@{2,})/g,'@')

works for any number of occorences.. @@, @@@, @@@@ etc

TWL
  • 216
  • 1
  • 4
  • replace looks fine too. I can even look for consecutive @s at the back end too. But I wanted it in the regex as I have a particular set of characters allowed. – Vineeth Bolisetty Nov 06 '13 at 13:26
2
str.replace(/@@/g,'@')

finds and replaces all instances of '@@' by '@'. Also works if you have more than 2 consecutive '@' signs. Doesn't replace single @ signs or things that aren't @ signs.

edit: if you don't have to replace but just want to test on it:

/@@/.test(str)
Nzall
  • 3,429
  • 5
  • 27
  • 58
1

Try this regex

/^(?!.*(.)\1)[a-zA-Z][a-zA-Z\d@]*$/

This regex will not allow @ consecutively

Rajdeep Singh
  • 17,174
  • 6
  • 49
  • 74