Manikandan Kannan
Manikandan Kannan

Reputation: 9014

Java regular expression for FileNameFilter implementation

I have a requirement to scan a folder and filter the files which matches a specific regular expression pattern.

Sample code in the accept method of the FileNameFilter


Scanner fileNameScanner = new Scanner(fileName);

Pattern mainPattern = Pattern.compile(this.pattern);

fileNameScanner.findInLine(mainPattern);

MatchResult result = fileNameScanner.match();

Now, I need a regular expression which filters the file which matches files with names like impl-2.0.xml and at the same time, it should not match impl-Test-2.0.xml.

I tried few settings but does not seem to work. It picks impl-Test-2.0.xml as well.

Upvotes: 4

Views: 4900

Answers (3)

cl-r
cl-r

Reputation: 1264

EDIT after comment

For an absolute path with size number limited

Pattern.compile(".*impl-[0-9]{1,2}\\.[0-9]{1,2}.xml");

For name file :

Pattern.compile("impl-[0-9]+\\.[0-9]+.xml");

EDIT 2

final Pattern patt = Pattern.compile("^\\p{Alnum}+\\-[0-9]+\\.[0-9]+.xml$");

Console

impl-3.0.xml
api-3.0.xml
x10-2.0.xml

You can replace ^ by a Java path separator if you grep an absolute path

Upvotes: 0

Duncan Jones
Duncan Jones

Reputation: 69339

I am happy with <one or more characters of any type>-<single digit>.<single digit>.xml

"characters of any type" is a dangerous statement in regular expressions! It is better if we restrict this by assuming you are happy with any letter or number. Based on that assumption, you want:

Pattern p = Pattern.compile("\\w+-\\d\\.\\d\\.xml");

Which will match characters in the range a-z, A-Z, 0-9 followed by a hyphen, one digit, a period, one digit and .xml.

Upvotes: 1

mmdemirbas
mmdemirbas

Reputation: 9158

See it in action on Regexr:

^\w+-\d\.\d\.xml

Upvotes: 1

Related Questions