开发者

Remove punctuation from string with Regex

开发者 https://www.devze.com 2023-03-02 04:35 出处:网络
I\'m really bad with Regex but I want to remove all these .,;:\'\"$#@!?/*&^-+ out of a string 开发者_开发百科string x = \"This is a test string, with lots of: punctuations; in it?!.\";

I'm really bad with Regex but I want to remove all these .,;:'"$#@!?/*&^-+ out of a string

开发者_开发百科
string x = "This is a test string, with lots of: punctuations; in it?!.";

How can I do that ?


First, please read here for information on regular expressions. It's worth learning.

You can use this:

Regex.Replace("This is a test string, with lots of: punctuations; in it?!.", @"[^\w\s]", "");

Which means:

[   #Character block start.
^   #Not these characters (letters, numbers).
\w  #Word characters.
\s  #Space characters.
]   #Character block end.

In the end it reads "replace any character that is not a word character or a space character with nothing."


This code shows the full RegEx replace process and gives a sample Regex that only keeps letters, numbers, and spaces in a string - replacing ALL other characters with an empty string:

//Regex to remove all non-alphanumeric characters
System.Text.RegularExpressions.Regex TitleRegex = new 
System.Text.RegularExpressions.Regex("[^a-z0-9 ]+", 
System.Text.RegularExpressions.RegexOptions.IgnoreCase);

string ParsedString = TitleRegex.Replace(stringToParse, String.Empty);

return ParsedString;

And I've also stored the code here for future use: http://code.justingengo.com/post/Use%20a%20Regular%20Expression%20to%20Remove%20all%20Punctuation%20from%20a%20String

Sincerely,

S. Justin Gengo

http://www.justingengo.com

0

精彩评论

暂无评论...
验证码 换一张
取 消