abdulrahmanAbdullah
abdulrahmanAbdullah

Reputation: 333

Regular expression to extract file name?

I want to remove last three character of filenames. To rename any files, i'm using:

String str = ""; // Here set File name, i.e. listFile.getName();  
String[] tempFile = str.split("[$^txt]");

This regex remove last three character it's OK, but when passing any file name containing "t OR x" the regex remove it. For example:

1) fileName.txt   -> result after split -> fileName -> OK. 
2) textfile.txt   -> result after split -> efile. -> remove any t OR x in file name.

My Q is : How i can remove only last three char.

Thank you

Upvotes: 1

Views: 927

Answers (3)

Furkan Toprak
Furkan Toprak

Reputation: 121

You could simply just use substring. String.substring is used for this purpose. In your case, you could simply use str.substring(0, str.length - 3) to get everything but the last 3 characters from the string. Besides this, you could use str.split.

Upvotes: 0

Akash
Akash

Reputation: 593

Try this RegEx instead:

 ^\\(.+\\)*(.+)\.(.+)$

Upvotes: 0

Björn Zurmaar
Björn Zurmaar

Reputation: 837

If you want to remove the file's extension a regex is much too complicated for the task. You can work with String.lastIndexOf(int) instead to determine the position of the file extension:

public static String extractFileName(final String fileName)
{
    final int dotIndex = fileName.lastIndexOf('.');
    return dotIndex < 0 ? fileName : fileName.substring(0,dotIndex);
}

Upvotes: 4

Related Questions