9

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

6 Answers 6

9

Use regex with a positive look ahead and capturing group.

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

Regex explanation here

Regular expression visualization

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for help! Much appreciated.
2

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

Comments

1

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.

Comments

1

Like @Jan I didn't pay attention to question closely. So @Pranav answer is working and is accepted but it has multiple unnecessary greedy dots. I'll reduce it to:

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

Live demo

Comments

1

Or just .*?(.).*?\1.* if you know already is [A-Za-z0-9].

For only check if matches (.).*?\1

Comments

1

If you find the character set restriction too limiting, use this:

function isNotUnique(inputString) {
    return !(inputString === [...new Set(inputString)].join(''));
}

It doesn't use regular expressions, but, handles most/all? characters as it relies on Set to enforce uniqueness. Example with Unicode:

let inputs = ['abc1', 'abc', 'abc11', '1abc1', 'aabc1', '☃☃', '☃', '☃abc', '(ฺ◣д◢)ฺ', '(ฺ◣д◢)'];
inputs.forEach(v => console.log(v + ': ' + isNotUnique(v)));

Outputs:

abc1: false
abc: false
abc11: true
1abc1: true
aabc1: true
☃☃: true
☃: false
☃abc: false
(ฺ◣д◢)ฺ: true
(ฺ◣д◢): false

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.