开发者

Is it possible to write a regular expression to check this:

Is it possible to write a regular expression to check whether all numbers of specific 10 digit number occured up to 3 times? for example return value for Regex.IsMatch("xxxx", "4433425425") is false. and for Regex.IsMatch("xxxx", "4463322545") is true. what is xxxx? in the first one i h开发者_C百科ave 4 occurrence of digit 4 and in second one non of digits occurred more than 3 times.


Will match any digit that has four or more instances

 string found =  Regex.Match(s,@"(\d).*\1.*\1.*\1").Groups[1].Value;

Just an example of how to use it

static void Main( string[] args )
{
     string fail = "1234567890";
     string s = "1231231222";
     string mTxt = @"(\d).*\1.*\1.*\1";
     Console.WriteLine( Regex.Match(s,mTxt).Success);
     Console.WriteLine(Regex.Match(fail, mTxt).Success);
}

Baised on @Brads Comments below use

([0-9]).*\1.*\1.*\1


Find a number occurring three times in a row:

(?=(0{3}|1{3}|2{3}|3{3}|4{3}|5{3}|6{3}|7{3}|8{3}|9{3}).{3}

Find a number occurring three times anywhere in the string:

(.?0.?){3}|(.?1.?){3}|(.?2.?){3}|(.?3.?){3}|(.?4.?){3}|(.?5.?){3}|(.?6.?){3}|(.?7.?){3}|(.?8.?){3}|(.?9.?){3}

Using backreferences (C/O @rerun):

([0-9]).*\1.*\1.*

NOTE: this will check the entire string for multiple characters. There is no limitation to the first 10 characters in the string. Let me know if you need that.


I'm going to risk downvotes here and suggest that regexes are most likely not the best tool for this job.

They have their place but I usually find that, if you're getting into "horrendous" territory with multiple backtracking or negative lookahead and lots of or clauses, you're probably better off tossing away the whole regex idea and writing a simple string scanning function which simply count each digit and ensures the counts are correct at the end. Pseudo-code something like:

def isValid (str):
    foreach ch in '0'..'9':
        count[ch] = 0
    foreach ch in str:
        if ch not in '0'..'9':
            return false
        count[ch] = count[ch] + 1
    foreach ch in '0'..'9':
        if count[ch] > 3:
            return false
    return true

That's my advice, take it or leave it, I won't be offended :-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜