Search code examples
sqlregexhostname

Replace hostname regex


I need extract host name and replace it by {HOST_NAME} I use this expression

SELECT regexp_replace(str, '[\/]{2}(.*)[\.|:]', '{HOST_NAME}', 1) from dual
str = http://localhost:8080/test
str = https://test-app.uk.ru/test

Expected result:

> http://localhost:8080/test -> http://{HOST_NAME}:8080/test
> https://test-app.uk.ru/test - > https://{HOST_NAME}.uk.ru/test

Result:

http://localhost:8080/test -> http:{HOST_NAME}8080/test
https://test-app.uk.ru/test - > https:{HOST_NAME}uk.ru/test

Solution

  • You may use the following approach:

    SELECT regexp_replace(str, '://[^.:]+', '://{HOST_NAME}', 1) from dual
    

    See the regex demo.

    The ://[^.:]+ matches:

    • :// - a literal substring
    • [^.:]+ - 1 or more chars other than . and :

    See an online demo:

    enter image description here