Anurag Ghosh
Anurag Ghosh

Reputation: 3

RegEx for not allowing double quotes not working

I am trying to form a RegEx which will allow alphanumeric along with some special characters ( @-_. ). I have tried to whitelist these special characters, but other special characters are also allowed. So I have tried to blacklist all the other special characters excluding the above mentioned. Used this:

/^([^\s!#$%&'()*+\/:;<=>?\[\\\]^`{|}~,][a-zA-Z@._0-9-]*[^\s!#$%&'()*+\/:;<=>?\[\\\]^`{|}~,])$/

How to add for double quotes so that it is not allowed in the string anywhere. Have tried \" but doesn't work.

Upvotes: 0

Views: 1211

Answers (3)

Malte Hartwig
Malte Hartwig

Reputation: 4555

You can use your whitelist approach, but need to put the - last: [@_.-]; or escape it: [@\-_.]

Otherwise, @-_ means "anything between ascii of @ and ascii of _".

Regex101.com is gold for such things, it explains every part of the regex.

Upvotes: 0

Mjx&#39;ware
Mjx&#39;ware

Reputation: 11

Use this one

Dim clean  as string = Regex.replace(tbname,"[^A-Za-z0-9\-/]","")

This one it blocks all special characters.

Upvotes: 1

SamWhan
SamWhan

Reputation: 8332

If I read you regex correct, and understand your wish:

^(                             # Start of string and capture group
[^\s!-,\/:-?\[\\\]^`{|}~,]     # Any character, BUT "blacklisted"
[\[email protected]]*                       # Any number of word characters, @, . or -.
[^\s!-,\/:-?\[\\\]^`{|}~,]     # Any character, BUT "blacklisted"
)$

It's simplified by using ranges. E.g. in a character class, !-, is the same as !"#$%&'()*+,, which also blacklists the unwanted ".

Upvotes: 1

Related Questions