开发者

submit url without any special characters

i have a text box where the user will the url in it and submit that url (it takes that url and search in our db)

but before it hit the db i want to make sure that there is no special characters in it:

below is the regular expression i am using but still accepting the special characters

here are the special characters i am trying to avoid < > % ( ) + ; these special caracters can be at the begining or end for an example:

()+;http://www.site.com/images.jpg()

for an example for ampersand (&) i use the below reg expression but somehow it ignores the begining.

Regex re = new Regex("\\(|\\)|\\<|\\>|\\\"|\\;|\n|\r|\\`|^&|&$"); 

so before i submit the above url i want to trip all the unwanted caracters.

static String StripSpcialChar(String param)        
{             
String result = null;             
if (param != null)             
{                                 
Regex re = new Regex("\\&|\\(|\\)|\\<|\\>|\\\"|\\;|\n|开发者_运维百科\r|\\`");                 
result = re.Replace(param, "");                 
result = result.Trim();             
}             
return result;         
} 


This should cover the special characters you've specified and correctly strips an ampersand from the beginning or end of the string. To account for multiple ampersands at the beginning or end of the string you need to use &+, where the + matches one or more ampersand.

string input = "&&&()+;http://www.site.com/images.jpg()&&&";
Regex re = new Regex(@"[()<>"";+\n\r`]|^&+|&+$");
string result = re.Replace(input, "");
Console.WriteLine(result);

Notice the use of the character class [...] which is much cleaner than multiple alternations with the pipe symbol. Within a character class there's no need to escape the characters. If you ever plan to match a dash you should place it at the beginning or end of the group to avoid accidentally specifying a range of characters. For example [()<>"";+\n\r-].


Usually you do not want to escape parameters your self, it's better to use built in escaping features like placeholders or whatever your DB API in C# has.

See:

  • http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson06.aspx
  • http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜