给定一个字符串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() 来完成。
- 找到从匹配结果的第一个索引到匹配结果的最后一个索引的子字符串,并将该子字符串添加到列表中。
- 完成上述步骤后,如果发现列表为空,则打印“-1”,因为字符串S 中不存在URL 。否则,打印存储在列表中的所有字符串。
下面是上述方法的实现:
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)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live