2

i have to extract a string between / and ?, i.e exampleproduct

https://local.host.com/order/faces/Home/myorder/exampleproduct?_adf.ctrl-state=mfun9p14r_19

how to write regular expression for this i am using this logic but i am unable to

 private static String extractPageNameFromURL(String urlFull) {    
    if (urlFull != null) {
        Pattern pattern = Pattern.compile("/(.*?).jspx?");
        Matcher matcher = pattern.matcher(urlFull);
        while (matcher.find()) {
            String str1 = matcher.group(1);
            String[] dataRows = str1.split("/");
            urlFull = dataRows[dataRows.length - 1];
        }
    }
    return urlFull;
}


 public static void main(String[] args) {
 System.out.println(DtmUtils.extractPageNameFromURL("https://local.host.com/order/faces/Home/myorder/exampleproduct?_adf.ctrl-state=mfun9p14r_19"));

}

Thanks Raj

3

4 Answers 4

1

If I'm following what you're asking, then you're attempting to pull exampleproduct from the URL.

Here's the regex to use to accomplish this. Group 1 should have the name after the last / and before the first ? after that slash.

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

See an example of the regex

^           -- Beginning of line anchor
.*          -- find 0 or more characters. Note the * is greedy.
\/          -- Find a literal /.
([^?]+)     -- Capture everything that is not a question mark
\?          -- Find a literal question mark
.*          -- now match everything after the question mark
$           -- end of line anchor

and here's a quick example of using it in Java. This is a quick example, and will need to be modified before using it.

String urlFull = "https://local.host.com/order/faces/Home/myorder/exampleproduct?_adf.ctrl-state=mfun9p14r_19";

Pattern pattern = Pattern.compile("^.*\\/([^?]+)\\?.*$");
Matcher matcher = pattern.matcher(urlFull);

matcher.find();

String p = matcher.group(1);
System.out.println(p);

I didn't follow why the original regex you wrote had the .jspx?, but if there's more to the problem you'll need to update the question to explain.

Sign up to request clarification or add additional context in comments.

Comments

0

To match exampleproduct in your input this lookahead based regex will work for you:

[^/]+(?=\?)

In Java code:

Pattern pat = Pattern.compile("[^/]+(?=\\?)");

RegEx Demo

Comments

0

This pattern might work for you \?(.*).

This regex finds a question mark and selects everything after it.

Comments

0

I tried this pattern with your path and it worked fine: ([\w_-]*)(\.)*([\w_-]*)?(?=\?)

It would also match, if your filename had a file ending.

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.