如何编写正则表达式以查找任何长度的字符串,仅包含3个不同的数字?

时间:2013-10-08 12:56:15

标签: regex

如何编写正则表达式以查找任意长度的字符串,仅包含3个不同的数字?

例如3213213312,679976679,并且不对应56785678

3 个答案:

答案 0 :(得分:4)

我同意正则表达式不是正确的工具,但它是可能的:

^(\d)\1*(?!\1)(\d)(?:\1|\2)*(?!\1|\2)(\d)(?:\1||\2|\3)*$

<强>说明:

^                 # Start of string
(\d)              # Match the first digit
\1*               # possibly more than once
(?!\1)            # Now match (as long as it's not the same one)
(\d)              # another digit
(?:\1|\2)*        # and possibly more repetitions of the first two.
(?!\1|\2)         # Then match (as long as it's one like before)
(\d)              # a third digit.
(?:\1||\2|\3)*    # Now match any number of one of the three digits
$                 # until the end of the string.

更好的解决方案,例如在Python中:

def threedigits(string):
    return string.isdigit() and len(set(string))==3

更具可读性(而且肯定更快)。

>>> threedigits("234")
True
>>> threedigits("234234")
True
>>> threedigits("2342345")
False
>>> threedigits("23232323")
False

答案 1 :(得分:3)

正则表达式(如果必须):Tim Pietzcker's answer

更好的方法(PHP):

$letters = count(array_unique(str_split("21323132")));//3

更好的方法(JavaScript):

var ltrs = '32132121232'.split('');
var unique=[];
for(var i=0,c=ltrs.length;i<c;i++)
{
    if(unique.indexOf(ltrs[i])==-1)
    {
        unique.push(ltrs[i]);
    }
}
console.log(unique.length);//3

更好的是,我必须指出,我考虑到灵活性,易读性和以后修改的能力。没有考虑性能测试或标准。

结束制作通用JavaScript解决方案:

function isxnums(str,x)
{
    x = x || 3;//Default number check to 3
    if(str.match(/^[0-9]+$/)==null) return false;
    for(var c=0,s2='';str!='';)
    {
        var num = str.match(/^([0-9])/)[1];
        s2 = str.replace(new RegExp(num,'g'),'');
        if(str != s2) c++;
        str = s2;
    }
    return c==x;
}

isxnums('123');//true
isxnums('3213213312');//true
isxnums('11111');//false
isxnums('11111',1);//true

答案 2 :(得分:1)

我不知道您使用的是哪种语言,但这种方式可能有所帮助:

  • 取字符串的第一个字符(数字)
  • 用空
  • 替换整个字符串中的char

执行上述步骤3次,

  • 如果无法完成3次,则返回false
  • 之后如果输入字符串仍然不为空,则返回false。
  • 否则为真