Reputation: 542
I am having a lot of problems filtering filenames in Java. I am using the PrimeFaces fileUpload tag, and I need to allow files that can be uploaded if they contain only alphanumeric characters followed by an extension, such as ".txt". To be specific, before the extension, the name must contain one or more of A-Z, a-z, or 0-9, with no spaces or other characters, followed by the extension ".txt", i.e. there must be one, and only one "." in the name, and that must be at the beginning of the extension.
So far all attempts of filtering names have not worked out properly, if I exclude .
, then it is also excluded from the extension. Filename should be of the type: abcXYZ123.txt
, aaaccc001.txt
, etc. but not ab.cd.txt
etc.
I have tried various combinations of /[A-Za-z0-9]+\\.txt$/
, /[^\\W_]+\\.txt$/
, /[\\p{Alnum}]\\.txt$/
, etc., but either they allow some invalid names, or exclude somevalid names.
Some help would be most appreciated.
Upvotes: 3
Views: 162
Reputation: 16037
I think you're on the right track with the $
at the end. I would match that with a caret ^
at the beginning to get
^[A-Za-z0-9]+\\.txt$
Just as $
means "the end of the line," so ^
means "the start of the line."
Testing this with the regex^[A-Za-z0-9]+\.txt$
, I get:
Matches
a.txt
abcXYZ123.txt
aaccc001.txt
No matches
a.b.c.txt
ab.cd.txt
.txt
As a side note, depending on your Regex implementation, alnum may or may not be equal to [A-Za-z0-9]
– it could contain numerals from other numbering systems (e.g. 六, which is six in Chinese).
Upvotes: 1