Jenananthan
Jenananthan

Reputation: 1401

Java Regex to find particular file

In one of my test case I want to copy particular jar of a component from one location to another location. e.g when target directory has only following jars

org.test.custom.search-4.2.2-SNAPSHOT-.jar
org.test.custom.search-4.2.2-tests-SNAPSHOT.jar

I want to copy the org.test.custom.search-4.2.2-SNAPSHOT-.jar . Where version of this jar can be changed at any time . So I can use the regex for that purpose as mentioned here[1]. But I want to know how to omit the other jar in regex. i.e want to omit the jar which has string "tests" in its name.

1.Regex for files in a directory

Upvotes: 8

Views: 763

Answers (4)

Bahramdun Adil
Bahramdun Adil

Reputation: 6079

You can use indexOf instead of regex to check if the file name containing the word "tests" like this:

if(fileName.indexOf("tests") >= 0) {
    // do what you want
}

Update: indexOf() will be much quicker than a regex, and is probably also easier to understand.

Upvotes: 1

Drgabble
Drgabble

Reputation: 628

Matches the SNAPSHOT exactly with any given version number, ignoring all others (including tests-SNAPSHOT):

org\.test\.custom\.search-\d+\.\d+\.\d+-SNAPSHOT-\.jar

Upvotes: 0

Hosam Aly
Hosam Aly

Reputation: 42443

One regex to match the main jar but not the test jar could be:

\w+-[\d.]+-(?!tests-).*\.jar

It has a negative matcher for the string "tests-". Note that you'll have to escape the backslashes when you put this regex into a string.

Upvotes: -1

xenteros
xenteros

Reputation: 15842

The regex based solution would be:

if (fileName.matches(".*tests.*")) {
    //do something
} else {
    //do something else
}

Upvotes: 1

Related Questions