string username = Regex.Replace(_username, @"(\s+|@|&|'|\(|\)|<|>|#)", "");
Answer from Mithilesh Gupta on Stack OverflowThis method will removed everything but letters, numbers and spaces. It will also remove any ' or " followed by the character s.
public static string RemoveSpecialCharacters(string input)
{
Regex r = new Regex("(?:[^a-z0-9 ]|(?<=['\"])s)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
return r.Replace(input, String.Empty);
}
public static string RemoveSpecialCharacters(string input)
{
Regex r = new Regex(
"(?:[^a-zA-Z0-9 ]|(?<=['\"])s)",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
return r.Replace(input, String.Empty);
}
Ryan's answer is right. Just add A-Z as well as many people would need it.
Regex remove all special characters except numbers?
Using regex to remove non-alphabetical characters in a string.
How do i remove special characters from a string?
Regex to remove special characters
Hi, I am trying to remove non-alphabetical characters from the following string.
let string = "Anne, I vote more cars race Rome-to-Vienna"
I can get the result I am looking for with the following...
let newString = string.toLowerCase().split('').filter(el => el !== ' ' && el !== '-' && el !== ',').join('')
However I would prefer to use a much shorter piece of code using regex. I have gone over a few regex examples and tutorials but it still kind of confused me. Does anybody know the simplest way to remove the unwanted characters from the above string?
Thanks!!!
Regex.Replace(input, "[^a-zA-Z0-9% ._]", string.Empty)
You can simplify the first method to
StringBuilder sb = new StringBuilder();
foreach (char c in input)
{
if (Char.IsLetterOrDigit(c) || c == '.' || c == '_' || c == ' ' || c == '%')
{ sb.Append(c); }
}
return sb.ToString();
which seems to pass simple tests. You can shorten it using LINQ
return new string(
input.Where(
c => Char.IsLetterOrDigit(c) ||
c == '.' || c == '_' || c == ' ' || c == '%')
.ToArray());
It really depends on your definition of special characters. I find that a whitelist rather than a blacklist is the best approach in most situations:
tmp = Regex.Replace(n, "[^0-9a-zA-Z]+", "");
You should be careful with your current approach because the following two items will be converted to the same string and will therefore be indistinguishable:
"TRA-12:123"
"TRA-121:23"
[^a-zA-Z0-9] is a character class matches any non-alphanumeric characters.
Alternatively, [^\w\d] does the same thing.
Usage:
string regExp = "[^\w\d]";
string tmp = Regex.Replace(n, regExp, "");
I got this from codewars. I used string.Replace() and an array to solve it but the top voted answer seemed more elegant. Problem is, I don't understand all of it.
public static string removeNoise(string equation) { return Regex.Replace(equation,@"[^a-zA-Z0-9\t. ?!]", ""); }
The problem is to remove any of these characters from a string: %$&/#·@|º\ª
The given parameter to test the method is "h%e&·%$·llo w&%or&$l·$%d".
After reading some msdn, here is what I think I understand so far:
-
It is using the Regex.Replace(string, string, string) overloaded method.
-
The first part of the solution says replace any characters that are not a to z, A to Z and 0 to 9 with an empty string literal.
-
The "." says to remove any "." characters.
What I don't understand:
-
What is the significance of the brackets []?
-
I don't see any tab characters in the given parameter. Why \t? Better yet, is \t a character that looks like multiple space characters?
-
Why the space between "." and ?!
-
What does ?! mean? msdn says "Zero-width negative lookahead assertion." It gives the example \b(?!un)\w+\b matches "sure", "used" in "unsure sure unity used". I can sort of infer what it means but I'm still not sure.
A minor detail: Lastly, I see conflicting results on system performance for using string.Replace(), Regex.Replace(), and stringbuild.Replace(). Articles from 2008/2009 say string.Replace() is faster but others say that Regex.Replace() is faster if performing more complicated tasks. Any recent update to this. This one isn't as key to my learning but would be interesting to note.
Edit: Resolved! Thanks all. Next step understand the stringbuilder.Replace() version of this.
Edit 2: For reference, my original solution was to place each special character in an array as a string[] and use a foreach loop with string.Replace(). Also, I found a stringbuild.Replace() version that's pretty cool. http://stackoverflow.com/questions/1120198/most-efficient-way-to-remove-special-characters-from-string
Edit 3: I posted an issue on the codewars discussion and I'm waiting for feedback because I found something else that should work (according to https://msdn.microsoft.com/en-us/library/az24scfc(v=vs.110).aspx):
return Regex.Replace(equation, @"[^\w ]", "");
It says to replace all non-alphanumeric characters or spaces with a blank. It works in Visual Studio 2015 but codewars check denies me (You failed the test for '%$&/#?@|??'.).
Your numbered questions are purely regex-related.
What is the significance of the brackets []?
In a regular expression, they denote a list of options. [abc] is about equivalent to a|b|c and [a-z] is about equivalent to [abcdefghijklmnopqrstuvwxyz].
I don't see any tab characters in the given parameter. Why \t? Better yet, is \t a character that looks like multiple space characters?
This is continuing the "not a-z, A-Z, 0-9" list by adding "not the \t character".
Why the space between "." and ?!
The space character is included in the list of characters to exempt.
What does ?! mean?
Both ? and ! are in the list of characters to exempt. Outside of square brackets is where they have a special meaning.
Thanks everyone. I got it.
I can either use
return Regex.Replace(equation, @"(?i)[^A-Z0-9\t. ?!]", "");
Or use the Regex.Replace(string, string, string, Regex Options) method instead like so:
return Regex.Replace(equation, @"[^A-Z0-9\t. ?!]", "", RegexOptions.IgnoreCase)