Rae Roth
Rae Roth

Reputation: 21

Java Regular Expression To Find PDF Files

Need help figure out how to tweak the below regular expression

Now we are using [0-9]+\.pdf to identify PDF files that starts with just a numbers “3005183198.pdf”

Now the files names have been changed to new format and i am not sure how to account for it.

What would the regular expression be to find a file pattern like this?

“3005183198.md515114F47DFD62791AC4C87527CED1AA5.PDF”

I know i should start with "[0-9]+" and end with \.pdf just not sure what i need to add to account for "." and the unknown string of letter and numbers.

Upvotes: 1

Views: 4040

Answers (4)

Alessio Demurtas
Alessio Demurtas

Reputation: 14

The expression you need to match your file names should be the following:

boolean res = testString.matches("[0-9]+[.][0-9A-Za-z]+[.][Pp][Dd][Ff]");

Use [.] to match the dot :)

Please tell me if I've been of help! :)

Upvotes: 0

Dorukhan Arslan
Dorukhan Arslan

Reputation: 2754

Alphanumeric regex:

"^[a-zA-Z0-9]+$"

OR

"^.+$"

Numeric regex:

"^[0-9]+$"

OR

"^\\d+$"

Dot regex:

"^\\.$"

Your regex:

"^\\d+\\..+\\.pdf$"

One or more numeric char + exactly one dot + one or more alphanumeric char + ".pdf"

Upvotes: 0

Lothar
Lothar

Reputation: 5459

Your pattern doesn't work if the filename really ends with .PDF because you only check for the lowercase variant. When you compile a pattern you can pass certain flags, so what you need should be covered by the following code:

Pattern pdfCheck = Pattern.compile("^.*\\.pdf$", Pattern.CASE_INSENSITIVE);

Upvotes: 0

Jose Martinez
Jose Martinez

Reputation: 12022

How about this:

“[0-9]+.*\\.pdf”

Upvotes: 2

Related Questions