c# - Create a static method that will parse any string to detect special characters and include \ before them -
in mvc-app want create method used everywhere avoid having special characters @, ", ' or else provoking major problem.
so i'm trying build method using regex parses string detect if there's special characters in string , put \ in front of them 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 many problems in code: 1) not familiar regex , have troubles figuring out wanted do. here, think trying detect if there characters other thos in regexitem; 2) when code hits string stringtoreturn =
line, app crashed says value cannot null.
can me out? thanks!
edit
i have been asked show example of special characters, here are:
'/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'
you idea, want avoid sending string database containing ', because interpreted end of string , provoke error.
if you're worried writing sql, check out: sqlparametercollection.addwithvalue.
as code, think it:
public static string parsestringforspecialchars(string stringtoparse) { const string regexitem = "[^a-za-z0-9 ]"; string stringtoreturn = regex.replace(stringtoparse, regexitem, @"\$&"); return stringtoreturn; }
Comments
Post a Comment