Java 如何检测和删除句子中的URL?

Java 如何检测和删除句子中的URL?,java,regex,string,parsing,url,Java,Regex,String,Parsing,Url,是否可以检测和删除句子中的任何类型的URL 例如: Today,wheather is cold.But I want to out. http://weathers.com..... And I will take a cup of tea... 今天,天气很冷。但我想出去。http://weathers.com..... 我要喝杯茶。。。 应该成为 Today,wheather is cold.But I want to out. And I will take a cup of tea..

是否可以检测和删除句子中的任何类型的URL

例如:

Today,wheather is cold.But I want to out. http://weathers.com..... And I will take a cup of tea... 今天,天气很冷。但我想出去。http://weathers.com..... 我要喝杯茶。。。 应该成为

Today,wheather is cold.But I want to out. And I will take a cup of tea... 今天,天气很冷。但我想出去。我要喝杯茶。。。
这取决于您希望匹配过程的全面程度。你可以试着用一些简单的方法

str.replaceAll("http://[^\\s]+", "")
e、 g

今天,天气很冷。但我想出去。我要喝杯茶。。。
如果希望更健壮的内容匹配有效URL,请使用更完整的URL正则表达式:

/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/ /^(https?:\/\/)([\da-z\.-]+)\([a-z\.]{2,6})([\/\w\.-]*)*\/$/
有关更全面的匹配,请参阅答案。

这取决于您希望匹配过程的全面程度。你可以试着用一些简单的方法

str.replaceAll("http://[^\\s]+", "")
e、 g

今天,天气很冷。但我想出去。我要喝杯茶。。。
如果希望更健壮的内容匹配有效URL,请使用更完整的URL正则表达式:

/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/ /^(https?:\/\/)([\da-z\.-]+)\([a-z\.]{2,6})([\/\w\.-]*)*\/$/
要获得更彻底的匹配,请参阅答案。

尝试下面的正则表达式

((http|ftp|https):\/\/)?[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?
要匹配有效的
URL
,以及以下代码,请选择您想要的:

    String str = "Today,wheather is cold. But I want to out. http://weathers.com..... And I will take a cup of tea";
    String regularExpression = "(((http|ftp|https):\\/\\/)?[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%&:/~\\+#]*[\\w\\-\\@?^=%&/~\\+#])?)";
    str = str.replaceAll(regularExpression,"");
    System.out.println(str);
编辑:


但是,此正则表达式不适用于所有类型的URL,因为它太复杂,很难找到匹配所有类型URL的完美正则表达式。

尝试下面的正则表达式

((http|ftp|https):\/\/)?[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?
要匹配有效的
URL
,以及以下代码,请选择您想要的:

    String str = "Today,wheather is cold. But I want to out. http://weathers.com..... And I will take a cup of tea";
    String regularExpression = "(((http|ftp|https):\\/\\/)?[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%&:/~\\+#]*[\\w\\-\\@?^=%&/~\\+#])?)";
    str = str.replaceAll(regularExpression,"");
    System.out.println(str);
编辑:


但是,此正则表达式不适用于所有类型的URL,因为它太复杂,很难找到匹配所有类型URL的完美正则表达式。

使用正则表达式。回答:请定义任何类型的URL<代码>https://?文件://?ftp://?scp://?smb://.. ... ?https://?文件://?ftp://?scp://?smb://,…和通常在Twitter上使用的短URL使用正则表达式。回答:请定义任何类型的URL<代码>https://?文件://?ftp://?scp://?smb://.. ... ?https://?文件://?ftp://?scp://?smb://,…还有通常在twitter上使用的短URL。真实URL(IRI)似乎更复杂@johnchen902是的,我在回答中提到了这个问题,谢谢。真实URL(IRI)似乎更复杂@johnchen902是的,我在回答中提到了这个问题,谢谢。