Home > Backend Development > C++ > How to Remove Non-Alphanumeric Characters in C# While Keeping Dashes and Spaces?

How to Remove Non-Alphanumeric Characters in C# While Keeping Dashes and Spaces?

DDD
Release: 2025-01-06 01:51:40
Original
309 people have browsed it

How to Remove Non-Alphanumeric Characters in C# While Keeping Dashes and Spaces?

Removing Non-Alphanumeric Characters with Exceptions

When dealing with strings, it may be necessary to remove non-alphanumeric characters while preserving specific symbols like dashes and spaces. Here's how to achieve this in C#:

Solution:

To remove all non-alphanumeric characters except dashes and space characters from a string, utilize regular expressions to replace them with an empty string.

C# Code:

string str = "My-string123!";
Regex rgx = new Regex("[^a-zA-Z0-9 -]");
str = rgx.Replace(str, "");
Console.WriteLine(str); // Output: My-string123
Copy after login

Explanation:

The pattern [^a-zA-Z0-9 -] matches any character that is not an alphanumeric character (a-z, A-Z, 0-9) or a dash (-) or a space ( ). By replacing this pattern with an empty string, it effectively removes all non-alphanumeric characters.

The above is the detailed content of How to Remove Non-Alphanumeric Characters in C# While Keeping Dashes and Spaces?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template