Regex match exactly

I have this regex:

^\\d{4}

to see if the string matches 4 digits, but it to ONLY match 4 digits ie:

1234 matches

1234gh does not.

cheers

^\d{4}$

if (Regex.IsMatch(r, “^\d{4}”))

this caused the d to be highlighted by VS as ‘Unrecognised escape sequence’

You forgot the “$” sign…

Try this:

if (Regex.IsMatch(r, @“^\d{4}$”))

cheers - that did it! What does the @ do then?

The @ makes the string a verbatim string. In a verbatim string \ (backslash) is literal and not an escape character which alters the meaning of the following char.

If the string had not been literal you would have needed to put in two \\s to make one \.

The regular expression is still ^\d{4}$ - it is just how to represent it in a string.