Take the 2-minute tour ×

I get "Bad Compile constant value" on this statement.

Regex objCheckNumber = new Regex("^(\d){4}$");

I simply want to set this up to check another string to see if the value entered is 4 digits.

share|improve this question

2 Answers 2

up vote 56 down vote accepted

C# is trying to interpret \d as an escape sequence, and \d is not a valid escape sequence (but \n and \t are, for example). You can either double up the backslashes to escape it ("^(\\d){4}$"), or you can prefix the constant string with an at-sign: @"^(\d){4}$".

share|improve this answer
-1: \d = single numeric digit in C#/.NET regex –  Paul Sasik Oct 13 '09 at 3:38
thanks, completely overlooked it probably because I was thinking too much about the regex and it's a string duh. –  CoffeeAddict Oct 13 '09 at 3:40
whoops, did not mean to up psasiks comment. –  CoffeeAddict Oct 13 '09 at 3:42
@psasik: Obviously \d holds meaning within a regular expression, but it does not hold meaning within a normal string. As an input to a regular expression, \d is two characters, whereas in a normal string, \n and \t get interpreted as one character. –  Mark Rushakoff Oct 13 '09 at 3:43
Don't worry, Mark Some of us are paying attention tonight. –  Joel Coehoorn Oct 13 '09 at 3:59

C# uses \ as an escape character. You need to double up the \ to \\.

Alternatively, place a @ character before the double-quote:

new Regex(@"^(\d){4}$")
share|improve this answer
The \ escapes the d which means single numeric character. With {4} he's looking for four of them in a row. –  Paul Sasik Oct 13 '09 at 3:31
@pasasik - yes, \d has special meaning to the regex engine, but you have to get that string to the regex engine first. Without doubling it or using @, the C# compiler thinks you mean \d as a 'special' character (like \t or \n) and tries (and fails) to handle it. –  Jonathan Rupp Oct 13 '09 at 3:36
i am testing in RegexHero: regexhero.net/tester and ... jeesh. i see my mistake. (Sorry about the downvote binarycoder, SO wouldn't let me reverse it...) –  Paul Sasik Oct 13 '09 at 3:40

Your Answer


