简体   繁体   English

如何在C#中使用正则表达式匹配规则

[英]how to match rules using regex in C#

I am new to regex stuff in C#. 我是C#中的正则表达式新手。 I am not sure how to use the regex to validate client reference number. 我不确定如何使用正则表达式来验证客户端参考号。 This client reference number has 3 different types : id, mobile number, and serial number. 该客户参考号具有3种不同的类型:id,手机号和序列号。

C#: C#:

string client = "ABC 1234567891233";

//do code stuff here:
if Regex matches 3-4 digits to client, return value = client id
else if Regex matches 8 digts to client, return value = ref no
else if Regex matches 13 digits to client, return value = phone no

I dont know how to count digits using Regex for different types. 我不知道如何使用正则表达式对不同类型的数字进行计数。 Like Regex("{![\\d.....}"). 就像Regex(“ {![\\ d .....}”))。

I don't understand why you're bent on using regular expressions here. 我不明白为什么您会在这里使用正则表达式。 A simple one-liner would do, eg. 一个简单的单线便可以做到,例如。 even such an extension method: 甚至是这样的扩展方法:

static int NumbersCount(this string str)
{
    return str.ToCharArray().Where(c => Char.IsNumber(c)).Count();
}

It's clearer and more maintainable in my opinion. 我认为它更清晰,更可维护。

You could probably give it a go with group matching and something along the lines of 您可能可以通过组匹配以及类似的方式进行尝试

"(?<client>[0-9]{5,9}?)|(?<serial>[0-9]{10}?)|(?<mobile>[0-9]{13,}?)"

Then you'd check whether you have a match for "client", "serial", "mobile" and interpret the string input on that basis. 然后,您将检查“ client”,“ serial”,“ mobile”是否匹配,并在此基础上解释输入的字符串。 But is it easier to understand? 但是更容易理解吗?

Does it express your intentions more clearly for those reading your code later on? 对于以后阅读代码的人,它是否更清楚地表达了您的意图?

If the requirement is such that these numbers must be consecutive (as @Corak points out)... I'd still write that iteratively, like so: 如果要求是这些数字必须是连续的(如@Corak指出的那样)...我仍然会迭代地编写它,如下所示:

/// <summary>
/// returns lengths of all the numeric sequences encountered in the string
/// </summary>        
static IEnumerable<int> Lengths(string str)
{
    var count = 0;
    for (var i = 0; i < str.Length; i++)
    {
        if (Char.IsNumber(str[i]))
        {
            count++;
        }
        if ((!Char.IsNumber(str[i]) || i == str.Length - 1) && count > 0)
        {
            yield return count;                
            count = 0;                    
        }
    }
}

And then you could simply: 然后您可以简单地:

bool IsClientID(string str)
{
    var lenghts = Lengths(str);
    return lenghts.Count() == 1 && lenghts.Single() == 5;            
}

Is it more verbose? 更详细吗? Yes, but chances are that people will still like you more than if you make them fiddling with regex every time the validation rules happen to change, or some debugging is required : ) This includes your future self. 是的,但是人们可能仍然会喜欢您,而不是每次验证规则发生变化或需要进行一些调试时都让他们对正则表达式摆弄:)这包括您的未来自我。

I'm not sure if I understood your question. 我不确定是否理解您的问题。 But if you want to get the number of Numerical Characters from a string you can use the following code: 但是,如果要从字符串中获取数字字符的数量,可以使用以下代码:

Regex regex = new Regex(@"^[0-9]+$");
string ValidateString = regex.Replace(ValidateString, "");
if(ValidateString.Length > 4 && ValidateString.Length < 10)
    //this is a customer id
....

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

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