Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 464
  • Last Modified:

Creating a regular expression in C#

I would like to create a regular expression in C# for a string that has an exact length of 9 characters and the first 4 chars are alphabets (uppercase and lowercase) and last 2 chars are digits [0-9] eg. abcd00078, qwerty976
0
TAMUQITS
Asked:
TAMUQITS
2 Solutions
 
Asim NazirCommented:
0
 
crysallusCommented:
Regex reg = new Regex(@"(?<![A-Z0-9])[A-Z]{4}[A-Z0-9]{3}[0-9]{2}(?![A-Z0-9])", RegexOptions.IgnoreCase);

Open in new window

0
 
MathiyazhaganCommented:
try this :
            string word = "qwerty976";
            bool bMatched = Regex.IsMatch(word, @"[a-zA-Z]{4}\w{3}\d{2}");

here:
[a-zA-Z]{4} - any alphabetic character , min of 4 chars
\w {3} - any alphanumeric character, min of 3 chars
\d{2} - any digits, min of 2 digits

hope this helps.
0
Free learning courses: Active Directory Deep Dive

Get a firm grasp on your IT environment when you learn Active Directory best practices with Veeam! Watch all, or choose any amount, of this three-part webinar series to improve your skills. From the basics to virtualization and backup, we got you covered.

 
MathiyazhaganCommented:
sorry ,  in above expression {n} specifies number of occurance, not min no.of occurance as I specified. That is,

[a-zA-Z]{4} - any alphabetic (of either case)  of 4 occurances
 \w {3} - any alphanumeric , of 3 occurances
\d{2} - any digits, of 2 occurances.





0
 
wdosanjosCommented:
I think you need to anchor the pattern otherwise strings with more than 9 chars will match also.  Something like this:

Regex.IsMatch(word, @"^[a-zA-Z]{4}\w{3}\d{2}$");

0
 
MathiyazhaganCommented:
Yes Wdosanjos,You are correct. I Forgot to anchor the expression between ^  and $ , so that It only accepts exact pattern defined by expression.
0

Featured Post

Get your Disaster Recovery as a Service basics

Disaster Recovery as a Service is one go-to solution that revolutionizes DR planning. Implementing DRaaS could be an efficient process, easily accessible to non-DR experts. Learn about monitoring, testing, executing failovers and failbacks to ensure a "healthy" DR environment.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now