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
644 views
in Technique[技术] by (71.8m points)

regex - 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}$

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.

Thanks

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You could use these expressions instead:

  • 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.

Notice that the last [a-zA-Z] can not be replaced by w because w includes the underscore character and digits.

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.


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

1.4m articles

1.4m replys

5 comments

57.0k users

...