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,671
  • 11
  • 54
  • 75

5 Answers5

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,720
  • 11
  • 37
  • 50
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,439
  • 5
  • 29
  • 59
1

Try this regex

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

This regex will not allow @ consecutively

Rajdeep Singh
  • 17,621
  • 6
  • 53
  • 78
0

I didn't find any pure regex solution that worked for your use-case

So here is mine:

^([a-z0-9]@?)*[a-z0-9]$
 |____________|______|
       |          |-> Makes sure your string ends with an alphanumeric character
       |-> Makes sure the start of the string is a mix of single @ or alphanumeric characters
       |   It has to start with an alphanumeric character
Nasta
  • 819
  • 8
  • 21