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.

1
  • 4
    and what have you tried?? Commented Nov 6, 2013 at 13:01

5 Answers 5

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
Sign up to request clarification or add additional context in comments.

2 Comments

This matches any repeated character. I think the question is specifically about the @ character. You might want to address that in your answer.
@Reeno sorry about that. I just wanted to explain more.
3
str.replace(/(@{2,})/g,'@')

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

1 Comment

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.
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)

Comments

1

Try this regex

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

This regex will not allow @ consecutively

3 Comments

This matches any repeated character. I think the question is specifically about the @ character. You might want to address that in your answer.
made the changes, have a look
@RajdeepSingh I tried again, it still doesn't allow any successive characters
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.