Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for removing only specific special characters from string

I'd like to write a regex that would remove the special characters on following basis:

  • To remove white space character
  • @, &, ', (, ), <, > or #

I have written this regex which removes whitespaces successfully:

 string username = Regex.Replace(_username, @"\s+", "");

But I'd like to upgrade/change it so that it can remove the characters above that I mentioned.

Can someone help me out with this?

like image 715
User987 Avatar asked Feb 04 '17 20:02

User987


People also ask

How do I remove a specific character from a string?

Using 'str. replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.

What does \+ mean in regex?

For examples, \+ matches "+" ; \[ matches "[" ; and \. matches "." . Regex also recognizes common escape sequences such as \n for newline, \t for tab, \r for carriage-return, \nnn for a up to 3-digit octal number, \xhh for a two-digit hex code, \uhhhh for a 4-digit Unicode, \uhhhhhhhh for a 8-digit Unicode.

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9.


1 Answers

 string username = Regex.Replace(_username, @"(\s+|@|&|'|\(|\)|<|>|#)", "");
like image 54
Mithilesh Gupta Avatar answered Sep 28 '22 20:09

Mithilesh Gupta