user1406476
user1406476

Reputation: 69

java regex get just the filename

need some help on pattern mathcing; I need to extract just the filename from a string like:

https://www.testsite.com/files/form/anonymous/api/library/ecb198be-1f05-4b0b-b0cd-7d878488a8c4/document/050cc508-1ea6-4b5f-a22b-b3edbdf6291f/media/x.jpg

just the x.jpg part

& also from this string:

<img alt="/JAGC/Images?action=AttachFile&amp;do=get&amp;target=Images/x.jpg">

& if they are the same image, then replace the target with the URL string.

I can regex out the the

any help please?

Upvotes: 0

Views: 2273

Answers (3)

Bohemian
Bohemian

Reputation: 425033

It's as simple as this:

String filename1 = url.replaceAll(".*/([^/]+)", "$1");
String filename2 = xml.replaceAll(".*/([^\"]+)\".*", "$1");
if (filename1.equals(filename2))
    xml = xml.replaceAll("(.*/)([^\"]+)(\".*)", "$1" + url + "$3");

Upvotes: 0

Grim
Grim

Reputation: 1986

Try this:

str.replaceAll("^.*([a-z]+\\.[a-z]+).*$","$1");

The () group the filename to $1.

Upvotes: 0

Arnold Galovics
Arnold Galovics

Reputation: 3416

It doesn't need any regexp.

Use like this:

String code = "...";
String filename = code.substring(code.lastIndexOf("/")+1, code.length());

Edit: And in the second case, you dont need the ending of the tag, so use code.length()-2

Upvotes: 7

Related Questions