yonikawa
yonikawa

Reputation: 609

tar extension match using regex

I have a directory with some image files. I want to move all those files to a different place as long as they are not tar extensions. What is the regex in Java to filter tar files?

This is my code:

String regex = "^[[a-z]\\.[^tar]$]*";

Upvotes: 0

Views: 680

Answers (3)

Niels
Niels

Reputation: 49929

You have several ways.

Use this regex

^.*\.(?!tar).*$

EndWith solution

if(!filename.endsWith(".tar"))

FileFilter - Link

And probably a few more. I think the endsWith is the fastest way, not regex, because that's pretty heavy operation.

Upvotes: 1

Braj
Braj

Reputation: 46871

Use String.matches() method to test a string for a match ignore case.

sample code:

String regex = "(?i).*\\.tar";
String fileName = "xyz.taR";
System.out.println(fileName.matches(regex)); // true

Upvotes: 0

Ryan J
Ryan J

Reputation: 8323

Try this:

// implement the FileFilter interface and override the accept method
public class ImageFileFilter implements FileFilter
{
  private final String[] filterExtensions =
    new String[] {"tar"};

  public boolean accept(File file)
  {
    for (String extension : filterExtensions)
    {
      // if the file name does not end with the extension, you can accept it
      if (!file.getName().toLowerCase().endsWith(extension))
      {
        return true;
      }
    }
    return false;
  }
}

Then you can get a list of files with this filter

File dir = new File("path\to\my\images");
String[] filesWithoutTars = dir.list(new ImageFileFilter());
// do stuff here

EDIT: Since the OP says he can't modify the java code, the following regex should do what you want: ^.*(?!\.tar)$

It will match anything from the beginning of the string, but asserts that the ".tar" portion at the end of the string will not match.

Upvotes: 1

Related Questions