Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

regex - Regular Expression to Match List of File Extensions

I would like to have a regular expression that will match a list of file extensions that are delimited with a pipe | such as doc|xls|pdf This list could also just be a single extension such as pdf or it could also be a wild card * or ? I would also like to exclude the | at the start or the end of the list and also not match the <>/:" characters.

I have tried the following but it doesn't account for a single * wildcard.

^([^|\<>/:"]|[^\<>:"])[^/\<>:"]*[^|/\<>:"]$

I have been on one of the online testers but can't seem to get over the final hurdle. If someone could point me in the right direction I would be most grateful.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can construct this from smaller building blocks. A single extension, excluding the characters you mention, would be:

[^\<>/:"]+

We should probably also exclude | since that's our delimiter:

[^\<>/:"|]+

This can automatically match wildcards as well, since they're not forbidden.

To construct the |-separated list from those is then easy:

[^\<>/:"|]+

followed by an arbitrary number of the same thing with a | before that:

[^\<>/:"|]+(|[^\<>/:"|]+)*

And if you want a complete string to match this, add the ^ and $ anchors:

^[^\<>/:"|]+(|[^\<>/:"|]+)*$

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...