I have the below urls :
https://comanage.example.edu/sp
https://wiki.cs.example.org/sp
https://intranet.math.example.edu/sp
https://myapp.example.com/sp
For these urls, I need to define a function that can detect them as URLs and then replace the https:// and sp path from them. Basically, I just need the hostname only.For ex, like below
https://comanage.example.edu/sp ->comanage.example.edu
https://wiki.cs.example.org/sp ->wiki.cs.example.org
https://intranet.math.example.edu/sp ->intranet.math.example.edu
https://myapp.example.com/sp ->myapp.example.com
For non urls, the function should detect and do not replace for them. Like below,
nonurl.example.com -> ***no replacement***
Can anyone please suggest me a solution for above,I do not have much knowledge on usage of regex.
2
Answers
The pattern
^https?://
should work here pretty easily for you. We can use that to replacehttp://
andhttps://
at the beginning of any string with an empty stringIn the pattern the
^
symbol denotes the beginning of the string. This means ifhttp://
somehow appeared in the middle of the string, it would not match that since it must be at the beginningThe
?
marks the previous character as optional. In the pattern thes
is optional to thathttp
andhttps
can be found.The
/
is there simply because the slashes have to be escaped.Simply use URL API