[英]Regex for removing only specific special characters from string
我想編寫一個正則表達式,可以在以下基礎上刪除特殊字符:
@
, &
, '
, (
, )
, <
, >
或#
我寫了這個正則表達式,它成功地刪除了空格:
string username = Regex.Replace(_username, @"\s+", "");
但我想升級/更改它,以便它可以刪除我提到的上述字符。
有人可以幫我解決這個問題嗎?
string username = Regex.Replace(_username, @"(\s+|@|&|'|\(|\)|<|>|#)", "");
使用字符集[charsgohere]
string removableChars = Regex.Escape(@"@&'()<>#");
string pattern = "[" + removableChars + "]";
string username = Regex.Replace(username, pattern, "");
我建議使用Linq而不是正則表達式 :
string source = ...
string result = string.Concat(source
.Where(c => !char.IsWhiteSpace(c) &&
c != '(' && c != ')' ...));
如果您要跳過許多字符,可以將它們組織成一個集合:
HashSet<char> skip = new HashSet<char>() {
'(', ')', ...
};
...
string result = string.Concat(source
.Where(c => !char.IsWhiteSpace(c) && !skip.Contains(c)));
您可以輕松使用Regex的Replace功能:
string a = "ash&#<>fg fd";
a= Regex.Replace(a, "[@&'(\\s)<>#]","");
import re
string1 = "12@34#adf$c5,6,7,ok"
output = re.sub(r'[^a-zA-Z0-9]','',string1)
^ 將用於除了括號中的提及(或用空格替換特殊字符)將用空格替換然后將在字符串中返回
結果 = 1234adfc567ok
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.