给定字符串S ,任务是从字符串查找并提取所有URL。如果字符串没有URL,则打印“ -1” 。
例子:
Input: S = “Welcome to https://www.geeksforgeeks.org Computer Science Portal”
Output: https://www.geeksforgeeks.org
Explanation:
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”
Output:
https://write.geeksforgeeks.org
https://www.geeksforgeeks.org
Explanation:
The given string contains two URLs ‘https://write.geeksforgeeks.org’ and ‘https://www.geeksforgeeks.org’.
方法:想法是使用正则表达式解决此问题。请按照以下步骤解决给定的问题:
- 创建一个正则表达式以从字符串提取所有URL,如下所述:
regex = “\\b((?:https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:, .;]*[-a-zA-Z0-9+&@#/%=~_|])”
- 用Java创建一个ArrayList并使用Pattern.compile()编译正则表达式。
- 将给定的字符串与正则表达式匹配。在Java,这可以通过使用Pattern.matcher()来完成。
- 查找从匹配结果的第一个索引到匹配结果的最后一个索引的子字符串,然后将此子字符串添加到列表中。
- 完成上述步骤后,如果发现列表为空,则在字符串S中不存在URL ,则打印“ -1” 。否则,打印列表中存储的所有字符串。
下面是上述方法的实现:
Java
// Java program for the above approach
import java.util.*;
import java.util.regex.*;
class GFG {
// Function to extract all the URL
// from the string
public static void extractURL(
String str)
{
// Creating an empty ArrayList
List list
= new ArrayList<>();
// Regular Expression to extract
// URL from the string
String regex
= "\\b((?:https?|ftp|file):"
+ "//[-a-zA-Z0-9+&@#/%?="
+ "~_|!:, .;]*[-a-zA-Z0-9+"
+ "&@#/%=~_|])";
// Compile the Regular Expression
Pattern p = Pattern.compile(
regex,
Pattern.CASE_INSENSITIVE);
// Find the match between string
// and the regular expression
Matcher m = p.matcher(str);
// Find the next subsequence of
// the input subsequence that
// find the pattern
while (m.find()) {
// Find the substring from the
// first index of match result
// to the last index of match
// result and add in the list
list.add(str.substring(
m.start(0), m.end(0)));
}
// IF there no URL present
if (list.size() == 0) {
System.out.println("-1");
return;
}
// Print all the URLs stored
for (String url : list) {
System.out.println(url);
}
}
// Driver Code
public static void main(String args[])
{
// Given String str
String str
= "Welcome to https:// www.geeksforgeeks"
+ ".org Computer Science Portal";
// Function Call
extractURL(str);
}
}
https://www.geeksforgeeks.org
时间复杂度: O(N)
辅助空间: O(1)