java在一行中查找和替换多个URL
所以,我的目标是创建一个URL缩短器,除了在一行中输入两个URL外,它是有效的
例如,如果我输入“laskjdflas www.google.com lakdsjfsa www.google.ca”,我会得到以下回应:
Please enter in a URL to shorten
laskjdf www.google.ca lksadjf www.google.com
laskjdf http://aman207.tk/9 lksadjf http://aman207.tk/9
laskjdf htt://aman207.tk/-4gi5 lksadjf htt://aman207.tk/-4gi5
(我知道最后两个链接缺少一个p)
这是我的代码:
Scanner keyboard=new Scanner(System.in);
System.out.println("Please enter in a URL to shorten");
URLget=keyboard.nextLine();
String originalMessage=URLget;
Pattern p = Pattern.compile("(?i)\\b((?:https?://|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:'\".,<>?«»“”‘’]))");
Matcher m = p.matcher(URLget);
StringBuffer sb = new StringBuffer();
while (m.find())
{
URLget=m.group(1);
m.appendReplacement(sb, "");
sb.append(URLget);
m.appendTail(sb);
String URL="http://www.aman207.tk/yourls-api.php?signature=0a88314b95&action=shorturl&url="+ URLget;
if (URLget.startsWith("http://")||URLget.startsWith("www."))
{
try {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new InputSource(new URL(URL).openStream()));
NodeList nodeList = doc.getElementsByTagName("shorturl");
for (int temp = 0; temp < nodeList.getLength(); temp++)
{
Node nNode = nodeList.item(temp);
Element eElement = (Element) nNode;
if(eElement.getAttribute("shorturl") != null)
{
String findShortURL= eElement.getTextContent();
String finalMessage = originalMessage.replaceAll("(?:http://|www.?)[\\w/%.-]+", findShortURL);
System.out.println(finalMessage);
}
}
}
}
}
我需要它做的是,在一行中替换每个URL。有人有什么建议吗?谢谢
编辑:
输入: 随机词[URL缩短(URL1)]更多随机词[URL缩短(URL2)]
输出:
相同的随机词[缩短的URL1]相同的随机词[缩短的URL1(它与第一个URL是相同的缩短的URL。我需要它像预期的输出一样)]
预期产出:
相同的随机词[缩短的URL1]相同的随机词[缩短的URL2]
# 1 楼答案
用以下语句替换
if
语句:在
for
循环外使用println
,让它只给您一次输出# 2 楼答案
我自己想出来的
这是工作代码