简体   繁体   English

用单个唯一字符替换字符串中的特殊字符

[英]Replacing special chars in a string with a single unique char

I have a string like so: 我有一个像这样的字符串:

string inputStr = "Name*&^%LastName*#@";

The following Regex will replace all the special chars with a '-' 以下正则表达式将所有特殊字符替换为“-”

Regex rgx = new Regex("[^a-zA-Z0-9 - _]");
someStr = rgx.Replace(someStr, "-");

That produces an output something like: Name---LastName--- 产生的输出类似:Name --- LastName ---

How do I replace '---' with a single '-' so the output looks like this: 如何用单个“-”替换“ ---”,因此输出如下所示:

Name-LastName

So the question is how do I replace all the special chars with a single '-'? 因此,问题是如何将所有特殊字符替换为单个“-”?

Regards. 问候。

Try this 尝试这个

Regex rgx = new Regex("[^a-zA-Z0-9 \- _]+");//note - character is escaped

or 要么

Regex rgx = new Regex("[^a-zA-Z0-9 _-]+");//or use - as last character

But this will give Name-LastName- Is this okay or..? 但这将给出Name-LastName-可以吗?

If you don't need - at last position you can use the following code as well. 如果不需要-在最后的位置,您也可以使用以下代码。 Credit goes to @MatthewStrawbridge. 归功于@MatthewStrawbridge。 You can see in comments. 您可以在评论中看到。

string someStr = rgx.Replace(inputStr, "-").TrimEnd('-');

will output Name-LastName . 将输出Name-LastName

Edit: As @pguardiario pointed in comments updated my answer to escape - since range( [] ) has special meaning for - character. 编辑:正如@pguardiario在评论中指出的那样,更新了我的转义答案-因为range( [] )对于-字符具有特殊含义。 If we need - as a literal we need to escape it or make it first or last character of the character class in order to behave as literal. 如果需要-作为文字,我们需要对其进行转义或使其成为字符类的第一个或最后一个字符,以使其表现为文字。

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

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