tags:

views:

150

answers:

8

Hi,

What will be the regular expression to accept 'CP123' First two letters CP and other 3 or 4 or 5 nos.

+9  A: 
CP[0-9]{3,5}
Canopus
thank you.In CP[0-9]{3,5} it gets CP123 but not accepts CP1 or CP72. I want all these to accept CP123, CP1234, CP1, CP34. Thanks
Waheed
here {x,y} defines the min and the max number of [0-9] to be matched. Change x and y to whatever you want.
Canopus
If you want the first number to be greater than zero: `CP[1-9][0-9]{2,4}`.
Gumbo
+3  A: 

This should work for all regex engines:

CP[0-9]{3,5}
soulmerge
A: 
"$CP123[3-5]^"
takete.dk
I think you switched the $ and the ^.
Nathan Fellman
as well as misunderstood the question I guess ^^
takete.dk
+1  A: 

even if your question it's not very clear this should work:

r'^CP[0-9]{3,5}$'
DrFalk3n
+6  A: 

This will match your requirements:

^CP\d{3,5}$

The ^ matches the beginning of the string, so that it doesn't allow any characters to the left of "CP".

\d matches a digit, {3,5} makes it match 3-5 digits.

The $ matches the end of the string, so that it doesn't allow any characrers after the digits.

If you are using the regular expression in a validation control, you can remove the ^ and $, as that is added by the control:

CP\d{3,5}
Guffa
The only other variation I can think is if the 'CP' should be case insensitive e.g. ^(?i)CP\d{3,5}$
it depends
A: 
Regex regxExp = new Regex( "CP[0-9]{3,5}" );
bool result = regxExp.IsMatch( //Expression );
Sauron
+2  A: 

As per update in comments:

CP\d{1,5}

if you want one to five digits following CP. Otherwise use

CP\d+

if you just want CP followed by at least one digit.

Brian Rasmussen
A: 

Thank you all

^[Cc][Pp]\d{1,5}$

is the desired answer of my question.

Thanks for helping me.

Waheed
Please accept your answer by click on tick mark.
Sauron