简体   繁体   中英

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

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..?

If you don't need - at last position you can use the following code as well. Credit goes to @MatthewStrawbridge. You can see in comments.

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

will output Name-LastName .

Edit: As @pguardiario pointed in comments updated my answer to escape - since range( [] ) has special meaning for - character. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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