需要Regex检查字符串中至少4个不同的字符

时间:2022-08-09 20:13:34

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.

我需要Regex检查字符串是否至少有4个惟一字符。例如,如果一个字符串是“test”,那么它就会失败,因为它有三个不同的字符,但是如果一个字符串是“test1”,那么它就会通过。

3 个解决方案

#1


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:

我不确定如何使用regex来实现这一点,也不认为这是解决问题的好方法。这里有一个更通用的函数,有规则的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/

您可以在这里看到它的工作:http://jsfiddle.net/jfriend00/bqBRv/

#2


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:

如果您愿意使用额外的库,那么undescore。js提供了一些实用功能,可以使这个查询非常简短和甜蜜:

function countUniqueCharacters(value) {
  return _.uniq(value.split("")).length;
}

#3


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");
}

#1


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:

我不确定如何使用regex来实现这一点,也不认为这是解决问题的好方法。这里有一个更通用的函数,有规则的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/

您可以在这里看到它的工作:http://jsfiddle.net/jfriend00/bqBRv/

#2


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:

如果您愿意使用额外的库,那么undescore。js提供了一些实用功能,可以使这个查询非常简短和甜蜜:

function countUniqueCharacters(value) {
  return _.uniq(value.split("")).length;
}

#3


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");
}