Rhys Hudspeth
Rhys Hudspeth

Reputation: 17

check for valid string format

i am trying to make a validaing system where it checks a string is in the correct format.

the required format can only contain numbers and dashes - and be ordered like so ***-**-*****-**-* 3-2-5-2-1. For example, 978-14-08855-65-2

can i use Regex like i have for a email checking system by change the format key @"^([\w]+)@([\w])\.([\w]+)$"

the email checking code is

public static bool ValidEmail(string email, out string error)
{
    error = "";
    string regexEmailCOM = @"^([\w]+)@([\w])\.([\w]+)$";            // allows for .com emails
    string regexEmailCoUK = @"^([\w]+)@([\w])\.([\w]+)\.([\w]+)$";  // this allows fo .co.uk emails
    var validEmail = new Regex(email);

    return validEmail.IsMatch(regexEmailCOM) || validEmail.IsMatch(regexEmailCoUK) && error == "") // if the new instance matches with the string, and there is no error
}

Upvotes: 1

Views: 67

Answers (1)

diredev
diredev

Reputation: 137

Regex is indeed a good fit for this situation.

One possible expression would be:

^\d{3}-\d\d-\d{5}-\d\d-\d$

This matches exactly 5 groups of only digits (\d) separated by -. Use curly brackets to set a fixed number of repeats.

Upvotes: 1

Related Questions