Regex "Unrecognized Escape Seq?"
-
I'm trying to validate a TextBox for a floating point or int value ONLY. Keep getting a compiler error of "Unrecognized Escape Seq". Regex theRegex = new Regex("[-+]?([0-9]*\.)?[0-9]+ "); A) A quicker better way to validate? B) Where is the code incorrect? thanks
-
I'm trying to validate a TextBox for a floating point or int value ONLY. Keep getting a compiler error of "Unrecognized Escape Seq". Regex theRegex = new Regex("[-+]?([0-9]*\.)?[0-9]+ "); A) A quicker better way to validate? B) Where is the code incorrect? thanks
The '\' right after the * character is what is causing the compiler to baulk. Either escape it ('\\') or make the string verbatim by prefixing the @ symbol (
Regex theRegex = new Regex(**@**"[-+]?([0-9]*\.)?[0-9]+ ");
) Regards Senthil _____________________________ My Blog | My Articles | WinMacro -
I'm trying to validate a TextBox for a floating point or int value ONLY. Keep getting a compiler error of "Unrecognized Escape Seq". Regex theRegex = new Regex("[-+]?([0-9]*\.)?[0-9]+ "); A) A quicker better way to validate? B) Where is the code incorrect? thanks
A. Specify the RegexOptions.Compiled flag when you create the object if you plan to use it more than once. It takes longer to create the object, but it runs faster. B. As regular expressions and C# strings use the same escape character, you have to escape the escape character. Use \\ to put \ in the string. Also, you are missing the ^ and @ to specify the beginning and end of the string. Without them, any string containing a number will be valid, for an example the string "We have 200 horses.". You have an extra space at the end of the pattern. Remove that. [0-9] can also be written as \d.
Regex theRegex = new Regex("^[-+]?(\\d*\\.)?\\d+@");
Or you can use an @-quoted string:Regex theRegex = new Regex(@"^[-+]?(\d*\.)?\d+@");
--- b { font-weight: normal; } -
I'm trying to validate a TextBox for a floating point or int value ONLY. Keep getting a compiler error of "Unrecognized Escape Seq". Regex theRegex = new Regex("[-+]?([0-9]*\.)?[0-9]+ "); A) A quicker better way to validate? B) Where is the code incorrect? thanks
The problem is the "\." - characters after the backslash are interpreted Escape Sequence, which in your case makes (luckily) no sense. Two ways to fix it:
Regex theRegex = new Regex("[-+]?([0-9]*\\.)?[0-9]+ "); Regex theRegex = new Regex(@"[-+]?([0-9]*\.)?[0-9]+ ");
---------------------- ~hamster1