Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve particular part of string

Tags:

java

string

regex

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?

like image 508
Hip Hip Array Avatar asked Dec 19 '25 18:12

Hip Hip Array


1 Answers

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.

like image 149
Brian Agnew Avatar answered Dec 21 '25 07:12

Brian Agnew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!