Verwijder interpunctie uit string met Regex

Ik ben echt slecht met Regex, maar ik wil al deze .,;:'”$#@!?/*&^-+ uit een string verwijderen

string x = "This is a test string, with lots of: punctuations; in it?!.";

Hoe kan ik dat doen?


Antwoord 1, autoriteit 100%

Lees eerst hiervoor informatie over reguliere expressies. Het is het leren waard.

U kunt dit gebruiken:

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

Wat betekent:

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

Uiteindelijk staat er “vervang elk teken dat geen woordteken of een spatie is door niets.”


Antwoord 2

Deze code toont het volledige RegEx-vervangingsproces en geeft een voorbeeld van Regex die alleen letters, cijfers en spaties in een tekenreeks houdt – waarbij ALLE andere tekens worden vervangen door een lege tekenreeks:

//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;

En ik heb de code hier ook opgeslagen voor toekomstig gebruik:
http: // Code.justingengo.com/post/use%20a%20regular%20Expression%20Alt%20Remove%20Alle%20Punctuation%20Vrom%20a%20string

Oprecht,

s. Justin Geno

http://www.justingengo.com

Other episodes