Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need Regex that check at least 4 different character in string

Tags:

jquery

I need Regex that checks if a String has at least 4 unique characters. For example, if a string is "test" then it fails because it have three different chars but if a string is "test1" then it passes.

like image 387
Amit Shah Avatar asked Mar 19 '12 06:03

Amit Shah


2 Answers

I'm not sure how to do that with a regex, nor would I expect that to be a good way to solve the problem. Here's a more general purpose function with regular javascript:

function countUniqueChars(testVal) {
    var index = {};
    var ch, cnt = 0;
    for (var i = 0; i < testVal.length; i++) {
        ch = testVal.charAt(i);
        if (!(ch in index)) {
            index[ch] = true;
            ++cnt;
        }
    }
    return(cnt);
}

function hasFourUniqueChars(testVal) {
    return(countUniqueChars(testVal) >= 4);
}

You can see it work here: http://jsfiddle.net/jfriend00/bqBRv/

like image 197
jfriend00 Avatar answered Sep 21 '22 01:09

jfriend00


If you are open to using additional libraries, undescore.js provides some utility functions that can make this a very short and sweet query:

function countUniqueCharacters(value) {
  return _.uniq(value.split("")).length;
}
like image 33
Chris Pitman Avatar answered Sep 21 '22 01:09

Chris Pitman