开发者

C# Regex to detect usage of Special characters

开发者 https://www.devze.com 2023-03-17 18:41 出处:网络
I want to filter out special characters in C#. Basically i want to allow A-Z, a-z, 0-9, hyphen, underscore, (, ), commas, spaces, \\, /, spaces.

I want to filter out special characters in C#. Basically i want to allow A-Z, a-z, 0-9, hyphen, underscore, (, ), commas, spaces, \, /, spaces. Everything开发者_StackOverflow中文版 else is not allowed.

I have come up with the following regex ->

[a-zA-Z0-9-\b/(),_\s]*

but this doesn't seem to work fine.

Am I missing something?


If you want to filter out characters that don't match those, use a ^ at the beginning of the character class:

[^a-zA-Z0-9\-\\/(),_\s]+

The + quantifier will match any chars not in the character class at least once. Also, hyphens are meta characters inside character classes, so you should escape the dangling one you have, as I have done in my example. Also, if you want to include \ as an allowed character, you also need to escape it inside a character class, like [\\].

Also, inside a character class (also known as a character set defined by [ ]), \b is a backspace character, not a word boundary.


^[a-zA-Z0-9\-_(),\s\\/]+$


it's for the whole line

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号