Reputation: 5319
I'm trying to write very simple regular expression - this world is entirely new for me so I need an help.
I need to validate the next pattern: starts with C0 and finish with 4 digits exactly for example:
C01245 - legal
C04751 - legal
C15821 - not legal (does not starts with 'C0')
C0412 - not legal (mismatch length)
C0a457 - not legal
I took "cheat sheet" and wrote the next pattern:
C0\A\d{4) which means (I think) : starts with C0 and continue with 4 digits but this pattern always return "false".
What wrong with my pattern?
Upvotes: 1
Views: 174
Reputation: 336
Please take a look at this Snippet ,
using System.IO;
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string input1 = "C0123456";
// input1 starts with C0 and ends with 4 digit , allowing any number of
// characters/digit in between
string input2 = "C01234";
// input2 starts with C0 and ends with 4 digit , without
// characters/digit in between
String pattern1=@"\b[C][0][a-z A-Z 0-9]*\d{4}\b";
String pattern2=@"\b[C][0]\d{4}\b";
Match m = Regex.Match(input1, pattern1);
if(m.Success)
Console.WriteLine("Pattern1 matched input1 and the value is : "+m.Value);
m = Regex.Match(input2, pattern2);
if(m.Success)
Console.WriteLine("Pattern2 matched input2 and the value is : "+m.Value);
m = Regex.Match(input1, pattern2);
if(m.Success)
Console.WriteLine("Pattern2 matched input1 and the value is : "+m.Value);
m = Regex.Match(input2, pattern1);
if(m.Success)
Console.WriteLine("Pattern1 matched input2 and the value is : "+m.Value);
}
}
Output:
Pattern1 matched input1 and the value is : C0123456
Pattern2 matched input2 and the value is : C01234
Pattern1 matched input2 and the value is : C01234
Upvotes: 0
Reputation: 10512
^C0\d{4,}$
The string must start ^
with C0
, followed by 4 or more digits \d{4,}
at the end of the string $
.
Simply take off the last $
if it's not actually at the end of the string.
And if you're not looking to sandwich more numbers in-between, just remove the comma..
Kudos to @femtoRgon for the \d{4,}
(see comments).
Upvotes: 1
Reputation: 32827
You have to use this regex
^C0\d{4}$
^
would mark the beginning of string
$
would mark the end of string
\d{4}
would match 4 digits
You could also do it this way
if(input.StartsWith("C0") &&
input.Length==6 &&
input.Substring(2).ToCharArray().All(x=>Char.IsDigit(x)))
//valid
else //invalid
Upvotes: 3
Reputation: 5775
if you go to http://gskinner.com/RegExr/ you can write this expression:
^(C0[0-9]*[0-9]{4})[^0-9]
And in the content you put:
C012345 - legal
C047851 - legal
C*1*54821 - not legal (does not starts with 'C0')
C0412 - not legal (mismatch length)
C0*a*4587 - not legal
And you will see that it only matches what you want.
Upvotes: -1