Input: S = “Welcome to https://www.geeksforgeeks.org Computer Science Portal”
The given string contains the URL ‘https://www.geeksforgeeks.org’.
Input: S = “Welcome to https://write.geeksforgeeks.org portal of https://www.geeksforgeeks.org Computer Science Portal”
The given string contains two URLs ‘https://write.geeksforgeeks.org’ and ‘https://www.geeksforgeeks.org’.
Approach: The idea is to use Regular Expression to solve this problem. Follow the steps below to solve the given problem:
- Create a regular expression to extract all the URLs from the string as mentioned below:
regex = “\\b((?:https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:, .;]*[-a-zA-Z0-9+&@#/%=~_|])”
- Create an ArrayList in Java and compile the regular expression using Pattern.compile().
- Match the given string with the regular expression. In Java, this can be done by using Pattern.matcher().
- Find the substring from the first index of match result to the last index of the match result and add this substring into the list.
- After completing the above steps, if the list is found to be empty, then print “-1” as there is no URL present in the string S. Otherwise, print all the string stored in the list.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with industry experts, please refer DSA Live Classes