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

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Ildar Galikov
  • 293
  • 4
  • 15

6 Answers6

9

Use regex with a positive look ahead and capturing group.

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

Regex explanation here

Regular expression visualization

Wenfang Du
  • 5,689
  • 6
  • 40
  • 66
Pranav C Balan
  • 110,383
  • 23
  • 155
  • 178
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
ninjawarrior
  • 318
  • 1
  • 7
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.

Jan
  • 40,932
  • 8
  • 45
  • 77
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

revo
  • 45,845
  • 14
  • 70
  • 113
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
jconder
  • 626
  • 3
  • 9
0

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

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

compact
  • 1
  • 1