3

I'm trying to extract a string between '/' and '.' of a URL. For example, I have a URL like "some.com/part1/part2/part3/stringINeed.xyz". I need to extract "stringINeed" from the above URL, the one between last '/' and the '.' nothing else.

So far, I tried the following and it gives an empty output:

import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

class Extract
{
    public static void main (String[] args) throws java.lang.Exception
    {
        String str = "part1/part2/part3/stringINeed.xyz" ;
        Pattern pattern = Pattern.compile("/(.*?).");
        Matcher matcher = pattern.matcher(str);
        if (matcher.find()) {
     System.out.println(matcher.group(1));
        }
    }
}

What is wrong with my code. Can anyone help?

2
  • Do you have a full URL or just a part of it? Commented Jul 2, 2014 at 21:43
  • I have a full URL like example.com/part1/part2 and so on.. Part URL's also work as I would eventually end up extracting the URI from the servlet request Commented Jul 2, 2014 at 21:45

2 Answers 2

1

Use this regex:

[^/.]+(?=\.[^.]+$)

See demo.

In Java:

Pattern regex = Pattern.compile("[^/.]+(?=\\.[^.]+$)");
Matcher regexMatcher = regex.matcher(subjectString);
if (regexMatcher.find()) {
    ResultString = regexMatcher.group();
} 

Explanation

  • [^/.]+ matches any chars that are not a slash or a dot
  • The lookahead (?=\.[^.]+) asserts that what follows is a dot followed by non-dots and the end of the string
Sign up to request clarification or add additional context in comments.

1 Comment

Thaks for your answer Zx81. Worked for me!
1

Without regex

str.substring(str.lastIndexOf("/"), str.lastIndexOf(".")).replaceAll("/", "");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.