views:

51

answers:

5

I'm trying to write a validator for an ASP.NET txtbox.

How can I validate so the regular expression will only match if the 6th character is a "C" or a "P"?

+10  A: 

^.{5}[CP] will match strings starting with any five characters and then a C or P.

MikeD
+2  A: 

^.{5}[CP] -- the trick is the {}, they match a certain number of characters.

zdav
+5  A: 

Depending on exactly what you want, you are looking for something like:

^.{5}[CP]

The ^ says to start from the beginning of the string, the . defines any character, the {5} says that the . must match 5 times, then the [CP] says the next character must be part of the character class CP - i.e. either a C or a P.

Stephen
Updated with a slight correction taken from Carl's post - thanks @Carl!
Stephen
+1 - Nicely explained.
DaveB
A: 

[a-zA-Z0-9]{5}[CP] will match any five characters or digits and then a C or P.

rgw_ch
This will not work if the first 5 are not alpha-numeric. OP doesn't specify whether or not they are so don't assume they are.
FrustratedWithFormsDesigner
+1  A: 

^.{5}[CP] has a few important pieces:

  • ^ = from the beginning
  • . = match anything
  • {5} = make the previous match the number of times in braces
  • [CP] = match any one of the specific items in brackets

so the regex spoken would be something like "from the beginning of the string, match anything five times, then match a 'C' or 'P'"

Carl