本文共 989 字,大约阅读时间需要 3 分钟。
假设我有一个String消息:
我想要一个函数返回String newmessage:
“您应该将file.zip上传到[第一个链接的缩短版本],而不是[第二个链接的简化版本].请重试.”
我已经有了URL缩短器的代码,这是我的URL检测代码,它将替换消息中的第一个URL:
if(message.contains("http://") || message.contains("https://")) {
String regex = "(?i)\\b((?:https?://|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:'\".,<>?«»“”‘’]))";
Matcher m = Pattern.compile(regex).matcher(message);
if (m.find()) {
String url = m.group();
String shorted = null;
try {
shorted = Shortener.GetShortedISGD(url);
} catch (IOException e1) {
// TODO Auto-generated catch block
}
}
String intercepted = message.replace(url, shorted);
e.setMessage(intercepted);
}
我将如何替换所有这些?
(我为此使用了Bukkit API,所以很多功能不是Java编写的).
我正在考虑将消息拆分为单词数组,然后评估每个单词是否将是URL,除非这样做可能没有进行优化.
解决方法:
使用appendReplacement和appendTail.请参阅Java教程中的example,以及更接近您尝试执行的操作的another example.
标签:java,string,regex,url
来源: https://codeday.me/bug/20191014/1911829.html
转载地址:https://blog.csdn.net/weixin_34007963/article/details/114604462 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!