匹配特定URL的java正则表达式

匹配特定URL的java正则表达式,java,android,regex,Java,Android,Regex,我曾经用php构建了一个程序,它使用非常特定的正则表达式来匹配链接,但是这种模式在java中似乎不起作用,我正在尝试找到与 "~http://(bit.ly|t.co)~" 在php中,这将匹配这样的链接,java等价物是什么 http://(bit\.ly|t\.co)/\w* 我想这个结果和上面的一样我试过这个: String str = "http://bit.ly/asdfsd"; if(str.matches("http://(bit\.ly|t\.co).+")){ S

我曾经用php构建了一个程序,它使用非常特定的正则表达式来匹配链接,但是这种模式在java中似乎不起作用,我正在尝试找到与

"~http://(bit.ly|t.co)~"
在php中,这将匹配这样的链接,java等价物是什么

http://(bit\.ly|t\.co)/\w*
我想这个结果和上面的一样

我试过这个:

String str = "http://bit.ly/asdfsd";

if(str.matches("http://(bit\.ly|t\.co).+")){
    System.out.println("hurray");
}

我想你在找我

String str = "http://t.co/UURRNlrK";
String p = "(http://(t\.co|bit\.ly).*)";

Pattern pattern = Pattern.compile(p);
Matcher matcher = pattern.matcher(str);

if(matcher.find())
System.out.println(matcher.group(0));
输出=
http://t.co/UURRNlrK

如果
str=”http://bit.ly/AenG5W“

输出=
http://bit.ly/AenG5W


这是一个适用于java的好方法。

bit.ly和t.co的匹配中的点需要转义,例如“http://(bit\.ly | t\.co)。+”否则它也会匹配bitfly。