使用正则表达式测试文件名 [英] Test filename with regular expression
问题描述
我正在尝试使用此模式测试文件名字符串:
I am trying to test a filename string with this pattern:
^[A-Za-z0-9-_,\s]+[.]{1}[A-Za-z]{3}$
我想确保有一个三个字母的扩展名并允许字母、数字和以下符号: - _ 、 \s 在它之前,但我不想在文件名中包含所有字母和字符.我可以只使用 * 而不是 + 但这会匹配 0 或更多,这不是有效的文件名.
I want to ensure there is a three letter extension and allow letters, numbers and these symbols: - _ , \s to precede it but I don't want to have to include all of the letters and characters in the filename. I could just use a * instead of a + but that would match 0 or more which wouldn't be a valid filename.
以下是规则应如何反应的一些示例:
Here are some examples of how the rule should react:
Correct file name.pdf - true
Correct, file name.pdf - true
Correct_file_name.pdf - true
Correctfilename.pdf - true
Incorrect &% file name.pdf - false
Incorrect file name- false
如果有人能指出我正确的方向就好了.
It would be great if someone could point me in the right direction.
谢谢
推荐答案
您可以改用以下表达式:
You could use these expressions instead:
\w
- 与[a-zA-Z0-9_]
相同\d
- 与[0-9]
相同\.
- 与[.]{1}
相同
\w
- is the same as[a-zA-Z0-9_]
\d
- is the same as[0-9]
\.
- is the same as[.]{1}
这将使您的正则表达式:
Which would make your regex:
^[\w,\s-]+\.[A-Za-z]{3}$
请注意,字符类中的文字破折号必须在第一个或最后一个或转义(我把它放在最后),但是你把它放在中间,它错误地变成了一个范围.
Note that a literal dash in a character class must be first or last or escaped (I put it last), but you put it in the middle, which incorrectly becomes a range.
注意最后一个 [a-zA-Z] 不能被 \w
替换,因为 \w
包含下划线字符和数字.
Notice that the last [a-zA-Z] can not be replaced by \w
because \w
includes the underscore character and digits.
@tomasz 是对的!\w
== [a-zA-Z0-9_]
(确认here),所以我改变了我的答案,从第一个字符类中删除了不必要的 \d
.
EDITED: @tomasz is right! \w
== [a-zA-Z0-9_]
(confirmed here), so I altered my answer to remove the unnecessary \d
from the first character class.
这篇关于使用正则表达式测试文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!