Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中删除文本中的链接?_Java - Fatal编程技术网

在Java中删除文本中的链接?

在Java中删除文本中的链接?,java,Java,我需要做些改变->你好,到这里来http://www.google.com 对于您的… 抓取链接,在我创建的方法中对其进行更改,然后像这样将其替换回字符串 ->你好,到这里来http://www.yahoo.com 对于您的… 以下是我到目前为止的情况: if(Text.toLowerCase().contains("http://")) { // Do stuff } else if(Text.toLowerCase().contains("https

我需要做些改变->
你好,到这里来http://www.google.com 对于您的…
抓取链接,在我创建的方法中对其进行更改,然后像这样将其替换回字符串

->
你好,到这里来http://www.yahoo.com 对于您的…

以下是我到目前为止的情况:

if(Text.toLowerCase().contains("http://"))
{
    // Do stuff                 
}
else if(Text.toLowerCase().contains("https://"))
{
   // Do stuff                  
}

我需要做的就是将字符串中的URL更改为其他内容。字符串中的Url并不总是相同的,因此我不能只说
replace(“http://www.google.com“,”)

您可以使用下面的代码从字符串中获取链接。我假设字符串将只包含.com域

            String input = "Hello, go here http://www.google.com";
        Pattern pattern = Pattern.compile("http[s]{0,1}://www.[a-z-]*.com");
        Matcher m = pattern.matcher(input);
        while (m.find()) {
            String str = m.group();
        }
使用正则表达式:

String oldUrl = text.replaceAll(".*(https?://)www((\\.\\w+)+).*", "www$2");

text = text.replaceAll("(https?://)www(\\.\\w+)+", "$1" + traslateUrl(oldUrl));

注意:代码已更改,以满足以下注释中的额外要求。

您是否尝试过类似的操作:

s= s.replaceFirst("http:.+[ ]", new link);
这将找到任何以http开头的单词,直到第一个空格,并替换为您想要的任何单词

如果要保留链接,可以执行以下操作:

String oldURL;
if (s.contains("http")) {
    String[] words = s.split(" ");
    for (String word: words) {
        if (word.contains("http")) {
            oldURL = word;  
            break;
        }
    }
    //then replace the url or whatever
}
你可以试试这个

private String removeUrl(String commentstr)
    {
        String urlPattern = "((https?|ftp|gopher|telnet|file|Unsure|http):((//)|(\\\\))+[\\w\\d:#@%/;$()~_?\\+-=\\\\\\.&]*)";
        Pattern p = Pattern.compile(urlPattern,Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(commentstr);
        int i = 0;
        while (m.find()) {
            commentstr = commentstr.replaceAll(m.group(i),"").trim();
            i++;
        }
        return commentstr;
    }

你说你需要两个字符是什么意思?好吧,我需要删除http://到空白处并获取该字符串。我说的对吗?我不知道这里的其他人,但我不知道你的最终目标是什么。对不起,让我澄清一下。在某个时候,可能会有一个.co.uk,这也是让它工作起来的困难之一。查看编辑。字符串中的Url并不总是这样,所以我不能只说replace(“)OK-现在试试看,然后我可以这样调用我的方法:text=text.replaceAll((.https?:/)www(.\\w+”,MyUrl());?是(可能)-但是告诉我你想保留
https
还是
http
,或者你想总是用
http
替换协议,我想保留它。谢谢。如果链接是co.uk呢?看起来不错,但需要先将URL转换成字符串,这样我才能将其插入我的方法中。@EliteGamer现在查看答案。@EliteGamer