简体   繁体   English

是否可以编写正则表达式来检查:

[英]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? 是否可以编写正则表达式来检查特定10位数的所有数字是否最多出现3次? for example return value for Regex.IsMatch("xxxx", "4433425425") is false. 例如, Regex.IsMatch("xxxx", "4433425425")返回值为false。 and for Regex.IsMatch("xxxx", "4463322545") is true. 并且对于Regex.IsMatch("xxxx", "4463322545")是真的。 what is xxxx? 什么是xxxx? in the first one i have 4 occurrence of digit 4 and in second one non of digits occurred more than 3 times. 在第一个中,我有4 occurrence的数字4 ,在第二个中,非数字出现超过3次。

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 @Brads上的评论下面的评论使用

([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): 使用反向引用(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. 字符串中的前10个字符没有限制。 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. 他们有他们的位置,但我通常会发现,如果你进入“可怕的”领域有多个回溯或负面的前瞻和许多or条款,你可能最好抛弃整个正则表达式的想法并写一个简单的字符串扫描功能,只需计算每个数字,并确保计数在最后是正确的。 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 :-) 这是我的建议,接受或离开它,我不会被冒犯:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM