tags:

views:

51

answers:

4

I have a string that contains colours in the form of "^##" where ## can be 00-99.

I wrote regex to detect and replace these colours:

Input = Regex.Replace(Input, "\^[0-9][0-9]", "");

However the compiler doesn't seem to like \^ as a means of detecting the "^" character (gives an invalid escape code error). So how do I go about looking for the ^ character in c# regex?

A: 

Try a double-slash "\\^"

The slash is a control character in creating the string object itself.

But you want the string to contain a slash itself.

Sanjay Manohar
+2  A: 

You can try using verbatim string in Regex

Input = Regex.Replace(Input, @"\^[0-9][0-9]", "");

If you want to learn more about string literals read this article on MSDN.

jethro
thanks works perfectly (baww can't set as accepted answer yet).
Blam
+2  A: 

That happens because, well, there's no such escape sequence (\^)

You can use:

  • C# verbatim strings: @"\^[0-9][0-9]"
  • Two backslashes instead of one: "\\^[0-9][0-9]"

Tips:

  • The character class [0-9] is equivalent to the shorthand \d
  • Instead of having [0-9][0-9] you could use [0-9]{2} (or \d{2}). This helps when you have more repetitions.

References:

Character classes, Repetition

NullUserException
Thanks for the extra tips, it's now at @"\^\d{2}", slightly less readable but I'll add a little comment in there. :D
Blam
@Blam No problem. Answer updated
NullUserException
@Blam Well, that depends on how familiar with regex the person reading is ;)
NullUserException
A: 

Since the C# compiler itself gives special meaning to a \ in a string, if you want a string to contain a \ you must do one of two things:

  • escape it by doubling it: \\

  • make the string a verbatim string, by preceding the opening " with a @ : @"\" - but note that this latter option changes how quotes (") in the string must be escaped

AakashM