简体   繁体   中英

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

Use regex with a positive look ahead and capturing group .

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

Regex explanation here

正则表达式可视化

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

Can be done with:

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

See a demo on regex101.com (actually, fo ll owing 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 @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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM