nocarrier nocarrier - 1 year ago 107
C# Question

C# Regex Validation Rule using Regex.Match()

I've written a Regular expression which should validate a string using the following rules:

  1. The first four characters must be alphanumeric.

  2. The alpha characters are followed by 6 or 7 numeric values for a total length of 10 or 11.

So the string should look like this if its valid:


C being any character and N being a number.

My expression is written:

My regex match code looks like this:

var cc1 = "FOOBAR"; // should fail.
var cc2 = "AAAA1111111111"; // should succeed

var regex = @"^[0-9A-Za-z]{3}[0-9A-Za-z-]\d{0,21}$";

Match match = Regex.Match( cc1, regex, RegexOptions.IgnoreCase );

if ( cc1 != string.Empty && match.Success )
//"The Number must start with 4 letters and contain no numbers.",
Error = SeverityType.Error

I'm hoping someone can take a look at my expression and offer some feedback on improvements to produce a valid match.

Also, am I use
correctly? If
, then does that mean that the string is valid?

dtb dtb
Answer Source

The regex for 4 alphanumeric characters follows by 6 to 7 decimal digits is:

var regex = @"^\w{4}\d{6,7}$";

See: Regular Expression Language - Quick Reference

The Regex.Match Method returns a Match object. The Success Property indicates whether the match is successful or not.

var match = Regex.Match(input, regex, RegexOptions.IgnoreCase);

if (!match.Success)
    // does not match
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download