Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex test in JavaScript if a string contains only unique characters

A string contains only [A-Za-z0-9] characters. I need to know if the tested string contains at least one repeating character.

The following should return false:

abc1
abc

The following should return true:

abc11
1abc1
aabc1

abca

like image 560
Ildar Galikov Avatar asked Sep 17 '16 06:09

Ildar Galikov


3 Answers

Use regex with a positive look ahead and capturing group.

/(?=^[A-Za-z0-9]+$)(.)+.*\1.*/

Regex explanation here

Regular expression visualization

like image 54
Pranav C Balan Avatar answered Oct 22 '22 00:10

Pranav C Balan


Try using this regex for checking whether the characters are unique in the string

var str = 'aabbcc';
var isRepeat = (/([a-zA-Z0-9]).*?\1/).test(str); //Checks for repeated character in string
like image 34
ninjawarrior Avatar answered Oct 22 '22 00:10

ninjawarrior


Can be done with:

^.*?(\w)\1.*?$

See a demo on regex101.com (actually, following matches as well).


Explanation:

If you don't mind that the character class [A-Za-z0-9] can contain _ as well, \w is a shortcut for [A-Za-z0-9_]. Afterwards, the whole expression is bound to the start (^) and end ($) of a line/string. Last but not least, the lazy .*? matches anything before and after, the (\w)\1 at least one repeating character.

If you do mind about the _, leave it as [A-Za-z0-9]:

^.*?([A-Za-z0-9])\1.*?$

Hint:

Thinking about it, I have misread your question. This approach will match words like aabc or abbc but not 1abc1 as required in your question. Use a positive lookahead for this as proposed by @Pranav. Although this does not answer the question someone might be interested in this very solution so I tend to leave the answer.

like image 39
Jan Avatar answered Oct 22 '22 00:10

Jan