简体   繁体   English

C# - 正则表达式 - 替换不匹配的字符

[英]C# - regex - replace non matching characters

[there are similar questions but none is giving a valid answer for my needs] [有类似的问题,但没有一个能满足我的需求]

I allow user to input text matching this regex :我允许用户输入与此正则表达式匹配的文本:

string validChars = @"^[A-Za-zÀ-ÖØ-öø-ÿ0-9\s\.\-\&\,\'\(\)_\/\""\!\:\%]*?$";

what I want to do is to remove characters that do NOT match that regex我想要做的是删除与该正则表达式不匹配的字符

how can I INVERT the regex so I can do我怎样才能反转正则表达式,这样我才能做到

invalidChars  = some_trick_to_invert_regex(validChars); 
text = Regex.Replace(text, invalidChars , "");

thanks for your help感谢您的帮助

You can whitelist the characters you want to keep by placing the ^ inside the brackets.您可以通过将^放在方括号内来将要保留的字符列入白名单。 Example:例子:

string validChars = @"[^A-Za-zÀ-ÖØ-öø-ÿ0-9\s\.\-\&\,\'\(\)_\/\""\!\:\%]";
string test = "abc#de";
var result = Regex.Replace(test, validChars, ""); //abcde

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM