tags:

views:

53

answers:

3

Need a regular expression to check if webpage has special characters in the comments field. Comments should only have characters,numbers and @ = - ' " . i inside the comments. I am using C#.net to check it

THis is the code I have and it does not work

 if (!Regex.IsMatch(comments.Text,@"^[a-zA-Z''-'\s]$"))
 {
     lblError.Text = "Please Check your Comment.";
     return false;
 }
+2  A: 

Try this:

[a-zA-Z0-9@=\-'"]+
Rubens Farias
In addition to meeting the stated requirements, this is the only answer that correctly escapes the hyphen. It looks the OP was trying to do that by surrounding it with single-quotes (`'-'`).
Alan Moore
A: 

You are checking if the comment contains only one character because of the interval between ^ and $. Just remove them and if I remember correctly what Regex.IsMatch does, it should work.

Regex.IsMatch(comments.Text,@"[^a-zA-Z''-'\s]")

On a side note, perhaps you should allow numbers, too.

Oh, and I should note that it will return true if any other character than those indicated is found.

zneak
if any character is found which is not in the list then it should retrun false and throw the error.
aloo
A: 

The regex should be something like @"[^\w\s''-'@\"]"

\w gives you the alphabetic characters (including accented character), numeric characters and the underscore

\s gives you the whitespace

(I escaped the ", but it may or may not be needed. It's a little after 3am and I'm a little fuzzy, so you may need to play with that a bit...)

James Hollingshead
The quotation mark doesn't need to be escaped for the regex compiler, but it does for the C# compiler. For that you use `""`, not `\"`.
Alan Moore
Thanks for the pointer on that. Like I said, it was 3am and I was basically dead in my chair
James Hollingshead