简体   繁体   English

用于验证文件和特殊字符的正则表达式

[英]Regular Expression for Validation of files and Special characters

I have a regex which validates only file to upload .doc , .docx , .DOCX , .rtf , and .pdf . 我有一个正则表达式,仅验证上传.doc.docx.DOCX.rtf.pdf See below the regex code: 请参见下面的正则表达式代码:

"^.+(.doc|.DOC|.docx|.DOCX|.rtf|.RTF|.pdf|.PDF)$" 

But in this scenario, I also want to validate the file name should not include more than one . 但是在这种情况下,我还想验证文件名不应包含多个. .

For ex: 例如:

A file name should not be like this: abc.abc.doc it should be like this: abc.doc . 文件名不能这样: abc.abc.doc它应该是这样: abc.doc

There are two general formulas for what you want to do. 您要执行的操作有两个通用公式。

First approach: say what you want 第一种方法:说出你想要的

(?i)^[a-z0-9_-]+\.(?:docx?|rtf|pdf)$

The (?i) makes it case-insensitive so that you don't have to repeat doc , DOC etc. For instance, you could have a doC or DoC extension, but it is not mentioned in the original alternation. (?i)使其不区分大小写,因此您不必重复docDOC等。例如,您可以具有doCDoC扩展名,但原始替代中未提及。

The allowable chars for the prefix are specified in [a-z0-9_-] , so if you want more chars you can add them there. 前缀允许的字符在[a-z0-9_-]中指定,因此,如果需要更多字符,可以在此处添加。

Second approach: say what you don't want 第二种方法:说出您不想要的内容

Another approach is to allow all characters in the prefix except a dot and perhaps a number of "bad characters": 另一种方法是允许前缀中的所有字符(除了点之外,还可以包括许多“不良字符”):

(?i)^[^.<>:"/\\|*?\t\r\n]+\.(?:docx?|rtf|pdf)$

Neither will be a perfect fit unless you know exactly what set of characters your file system will allow. 除非您确切知道文件系统允许的字符集,否则两者都不是完美的选择。

^[^.]+([.]doc|[.]DOC|[.]docx|[.]DOCX|[.]rtf|[.]RTF|[.]pdf|[.]PDF)$

[^.]+ matches one or more characters which are not a period. [^.]+匹配一个或多个非句点字符。

EDIT: As Jongware mentioned, the periods inthe "OR" list should match the period literal. 编辑:如Jongware所述,“或”列表中的句点应与句点文字匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM