简体   繁体   English

正则表达式替换客户定义的特殊字符

[英]Regex replace special characters defind by client

I need ac# function which will replace all special characters customized by the client from a string Example 我需要ac#函数,它将替换客户端从字符串中自定义的所有特殊字符

 string value1 = @"‹¥ó׬¶ÝÆ";
 string input1 = @"Thi¥s is\123a strÆing";
 string output1 = Regex.Replace(input1, value1, "");

I want have a result like this : output1 =Thi s is\\123a str ing 我想要这样的结果: output1 =Thi s is\\123a str ing

Why do you need regex? 为什么需要正则表达式? This is more efficient, concise also readable: 这样更高效,简洁也可读:

string result = string.Concat(input1.Except(value1));

If you don't want to remove but replace them with a different string you can still use a similar(but not as efficient) approach: 如果您不想删除而是将其替换为其他string ,则仍然可以使用类似(但效率不高)的方法:

string replacement = "[foo]";
var newChars = input1.SelectMany(c => value1.Contains(c) ? replacement : c.ToString());
string result = string.Concat( newChars ); // Thi[foo]s is\123a str[foo]ing

Someone asked for a regex? 有人要求使用正则表达式吗?

string value1 = @"^\-[]‹¥ó׬¶ÝÆ";
string input1 = @"T-^\hi¥s is\123a strÆing";

// Handles ]^-\ by escaping them
string value1b = Regex.Replace(value1, @"([\]\^\-\\])", @"\$1");

// Creates a [...] regex and uses it
string input1b = Regex.Replace(input1, "[" + value1b + "]", " ");

The basic idea is to use a [...] regex. 其基本思路是使用[...]正则表达式。 But first you have to escape some characters that have special meaning inside a [...] . 但是首先,您必须转义一些在[...]中具有特殊含义的字符。 They should be ]^-\\ Note that you don't need to escape the [ 它们应为]^-\\请注意,您无需转义[

note that this solution isn't compatible with non-BMP unicode characters (characters that fill-up two char ) A solution that is compatible with them is more complex, but for normal use it shouldn't be a problem. 请注意,此解决方案与非BMP unicode字符(填充两个char不兼容。与它们兼容的解决方案更为复杂,但是对于正常使用而言,这不是问题。

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

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