How to replace all non-valid characters in string?

Viewed 57

How would I go about in replacing every character in a string which are not the following: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.@-

with -

So for example, the name Danny D'vito would become DannyD-vito

My inital thought was converting string to char[] and looping through and checking each character, then convert back to string. But my hunch is telling me there must be an easier way to do this

1 Answers

Regex.Replace() approach

string input = "Danny D'vito";
string result = new Regex("[^a-zA-Z0-9_.@-]").Replace(input, "-");
Related