How to restrict some file types and allow all othe

2019-03-05 04:34发布

I want to restrict few file types format and allow all others in regular expression validation expression. What i have try is specify some allowed and some restricted file types but i want to specify restricted file types and allow all others type to be uploaded.

I am using regular expression with asp.net file upload control. My regular expression looks like this right now

^.*\.(csv|xlsx|xls|doc|docx|pdf|txt|zip|(?!exe)|(?!bat)|(?!msi))$

Its working fine and restricting exe bat and msi but i want to allow all other file formats

1条回答
Summer. ? 凉城
2楼-- · 2019-03-05 05:11

Use a negative lookbehind:

/^.*(?<!\.(exe|bat|msi))$/i

The negative lookaheads you're using aren't helping you. At all. They're trivially true because you're trying to match them at the end of the string, and lookarounds don't consume anything, so the last position in the string can't have exe or bat after it.

A step by step explanation, for posterity's sake:

^

Match the start of the string, as I'm sure you know.

.*

consume the whole string.

(?<! ... )

Look back and make sure we haven't consumed....

\.

A literal dot, followed by...

(exe|bat|msi)

any of our verbotten file types.

$

then match the end of the string.

I also chose to make it case insensitive.

Edit, for js:

/^(.(?!\.(exe|bat|msi)$))*/i

Moar different explanation:

^

Top of string

(

Start group

.

Arbitrary Character

(?!...)

Negative lookahead. Not followed by:

\.

Literal dot.

(exe|bat|msi)

Forbidden File types.

$

End of string

)*

Close group and match that an arbitrary number of times.

查看更多
登录 后发表回答