Create a static method that will parse any string to detect special characters and include \ before them

In my MVC-App I want to create a method that will be used everywhere to avoid having any special characters like @, ", ' or anything else provoking a major problem.

So I'm trying to build this method using a regex that parses a string to detect if there's any special characters in the string and put a \ in front of them to make them harmless.

public static string ParseStringForSpecialChars(string stringToParse)
{
     const string regexItem = "^[a-zA-Z0-9 ]*$";

     string stringToReturn = Regex.Replace(stringToParse, regexItem, "\\");

     return stringToReturn;
}

There are many problems in my code: 1) I am not familiar with regex and I have troubles figuring out what I wanted to do. Here, I think I was trying to detect if there were any characters other than thos in the regexItem; 2) When the code hits the string stringToReturn = line, my app crashed as it says that the value cannot be null.

Can anyone help me out? Thanks!

EDIT

I have been asked to show an example of special characters, here they are:

'/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'

You get the idea, I just want to avoid sending a string to the database containing a ', because that will be interpreted as then end of a string and will provoke an error.

Answers


If you're worried about writing to sql, check out: SqlParameterCollection.AddWithValue.

As for your code, I think this is it:

public static string ParseStringForSpecialChars(string stringToParse)
{
    const string regexItem = "[^a-zA-Z0-9 ]";

    string stringToReturn = Regex.Replace(stringToParse, regexItem, @"\$&");

    return stringToReturn;
}

Need Your Help

Simple Server/Client Java tutorial

java mysql tomcat

I need to build a simple java server . The only thing i need to do is basic stuff and in particular , wait to GET a json file and store it in my sql database.

Primitive type and reference type objects

c# static primitive-types reference-type

I have an exam question from a past paper that I'm trying to answer:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.