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.
Asked
Active
Viewed 371 times
5
-
Do **Not** Use a "regular expression" for this. A regular expression **cannot handle this problem** well. (Yes, it's *possible*, fsvo, but it's a nightmare and limited to a relatively small upper-bound length.) – Mar 19 '12 at 06:07
-
Actually, that is not regular. – Matthias Mar 19 '12 at 06:09
3 Answers
6
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/

jfriend00
- 683,504
- 96
- 985
- 979
-
-
@jfriend00, What's with charAt() instead of indexing? Is it faster? – mowwwalker Mar 19 '12 at 06:18
-
@Walkerneo - I've just gotten in the habit of using `.charAt()`. [This other SO question/answer](http://stackoverflow.com/questions/5943726/string-charatx-or-stringx) suggests there are reasons why `.charAt()` is better than array notation for a bunch of reasons, most notably that older versions of IE don't like the array notation. – jfriend00 Mar 19 '12 at 06:22
1
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;
}

Chris Pitman
- 12,990
- 3
- 41
- 56
0
var str = "abcdef"
var counter = 0;
hash = new Object();
var i;
for(i=0; i< str.length; i++){
if(!hash[str.charAt(i)]){
counter +=1; hash[str.charAt(i)]=true
}
}
if(counter < 4){
console.log("error");
}

gayavat
- 18,910
- 11
- 45
- 55
-
-
-
1But you only interate up to string.length - 2, notice the "i< string.length -1". This is part of why I dislike explicit for loops, people mess them up all the time. – Chris Pitman Mar 19 '12 at 06:39