Theomax
Theomax

Reputation: 6792

ASP.NET - Regular expression to exclude specific characters

I need a regex that can accept all letters (A-Z which are case sensitive), numbers (0-9), spaces and most characters. The field must not accept accented characters (ÁÉÚÍÓ), tabs, or the following characters: backslash (), less than (<), greater than (>), tilde (~), equals (=), double quotes (”) or comma (,)

Any ideas on what sort of regex I would need for this?

Upvotes: 0

Views: 4535

Answers (2)

stema
stema

Reputation: 92976

I think this should the characters you want

(?:[^\p{L}\\<>~=",\t]|[A-Za-z])

[] denotes a character class, there you can put all characters in, that you want to allow

[^] denotes a negated character class, all characters inside are not allowed.

So, I don't know a predefined class that contains all letters that are not in A-Z, there fore I would go for an alternation.

The first negated class contains all letter in \p{L}, and the rest are the other characters you don't want to allow, but since you want to allow A-Z and they are also in \p{L} you have to allow them again. That is done in the second part (the | is an alternation) where I allow [A-Za-z].

So the complete regex should look something like this

^(?:[^\p{L}\\<>~=",]|[A-Za-z])+$

Upvotes: 3

npinti
npinti

Reputation: 52185

Something like this should work:

^([A-Za-z0-9 ]+)$

It will match foo bar 1234 FOO BAR but not foo bar 1234 FOO BAR dd or foo bar 1234 FOO BAR\

Note: You can then add the most characters within the square bracket.

Edit: foo bar 1234 FOO BAR dd contains a tab (\t) character but it is being shrunken down.

Upvotes: 3

Related Questions