regex constructor doesn't like \d

  • Thread starter Thread starter Dan Holmes
  • Start date Start date
D

Dan Holmes

i have this:
new System.Text.RegularExpressions.Regex("^\d+$") // \d by itself
failed as well.

but the compiler generates "unrecognized escape sequence". so i changed
it to this:

new System.Text.RegularExpressions.Regex("^[0-9]+$")

and it worked fine.

What am i doing wrong? Also are the ^ and $ reguired if i use the \d?

This is vs2005 if that matters.

dan
 
Dan said:
i have this:
new System.Text.RegularExpressions.Regex("^\d+$") // \d by
itself failed as well.

but the compiler generates "unrecognized escape sequence". so i changed
it to this:

new System.Text.RegularExpressions.Regex("^[0-9]+$")

and it worked fine.

What am i doing wrong?

In C# syntax, the backslash (\) is an escape character in string
literals. For example, it is used to express double quotes in strings
(as just typing a double quote would end the string literal), eg:

string StringWithAQuote = "This is a doublequote \" that was a doublequote";

Because of this, to express an actual backslash in a string literal, you
must use the escape sequence \\ (that is, a double backslash):

new System.Text.RegularExpressions.Regex("\\d+")

Alternatively, use the @ syntax for string literals that means 'do not
interpret escape sequences in this literal; accept all characters
literally':

new System.Text.RegularExpressions.Regex(@"\d+")

Also are the ^ and $ reguired if i use the \d?

Your problem was not the contents of the regex pattern, just getting it
into the regex itself. Use ^ and $ if it makes sense for whatever you
want to match against.
This is vs2005 if that matters.

I think this hasn't changed since C# 1.0.
 
Back
Top