0

The following query extracts the last two parts from a url. I want to extract the second last part from the url excluding the last.

SELECT substring(url,'/[^/]+/[^/]+$') FROM url_time;

Suppose I give input as Input : http://stackoverflow.com/questions/ask then I wish to get Output : /questions

Sorry if it is a trivial question . I have not been able to get to the required solution.

Any help is appreciated.

1 Answer 1

1

regexp_replace and capture groups will do it:

SELECT REGEXP_REPLACE ( url,'^.*/([^/]+)/[^/]+$', '\1' ) FROM url_time;

The initial ^.* consumes the beginning of the url. The parenthesis () around the first [^/]+ indicate a capture group, \1 replaces the entire match with the value of the capture group in output.

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

2 Comments

SELECT regexp_replace('stackoverflow.com/questions/ask','/([^/])+/[^/]+$','\1') AS action; gives me stackoverflow.coms as the answer as of now. I am trying to experiment with it though.
Yeah, I caught that too, answered before I tested. See my edit.

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.