Hip Hip Array
Hip Hip Array

Reputation: 4753

How to retrieve particular part of string

I have got a directory listing as a String and I want to retrieve a particular part of the string, the only thing is that as this is a directory it can change in length

I want to retrieve the file name from the string

"C:\projects\Compiler\Compiler\src\JUnit\ExampleTest.java"
"C:\projects\ExampleTest.java"

So in these two cases I want to retrieve just ExampleTest (the filename can also change so i need something like get the text before the first . and after the last \). Is there a way to do this using something like regex or something similar?

Upvotes: 2

Views: 182

Answers (5)

Anirudha
Anirudha

Reputation: 32787

This is the regex in c# and it works in java :P too.Thanks to Perl.It matches in Group[1]

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

Upvotes: 1

Gopal SA
Gopal SA

Reputation: 959

Java code

String test = "C:\\projects\\Compiler\\Compiler\\src\\JUnit\\ExampleTest.java";
String arr[] = test.split("\\Q"+"\\");
System.out.println(arr[arr.length-1].split("\\.")[0]);

Upvotes: 1

maba
maba

Reputation: 48045

File file = new File("C:\\projects\\ExampleTest.java");
System.out.println(file.getAbsoluteFile().getName());

Upvotes: 1

helios
helios

Reputation: 13841

new File(thePath).getName()

or

int pos = thePath.lastIndexOf("\\");
return pos >= 0? thePath.substring(pos+1): thePath;

Upvotes: 3

Brian Agnew
Brian Agnew

Reputation: 272237

Why not use Apache Commons FileNameUtils rather than coding your own regular expressions ? From the doc:

This class defines six components within a filename (example C:\dev\project\file.txt):

the prefix - C:\
the path - dev\project\
the full path - C:\dev\project\
the name - file.txt
the base name - file
the extension - txt

You're a lot better off using this. It's geared directly towards filenames, dirs etc. and given that it's a commonly used, well-defined component, it'll have been tested extensively and edge cases ironed out etc.

Upvotes: 6

Related Questions