2012-04-16 149 views
1

我有一个字符串为:“这是一个URL http://www.google.com/MyDoc.pdf应该使用”子之间的两个

我只需要提取从HTTP开始,在PDF结束的网址: http://www.google.com/MyDoc.pdf

String sLeftDelimiter = "http://"; 
String[] tempURL = sValueFromAddAtt.split(sLeftDelimiter); 
String sRequiredURL = sLeftDelimiter + tempURL[1]; 

这使我的输出为“http://www.google.com/MyDoc.pdf应该使用”

需要帮助的这一点。

+0

与此相关的问题,请检查一下: [如何检测URL字符串中的存在] [1] [1 ]:http://stackoverflow.com/questions/285619/how-to-detect-the-presence-of-url-in-a-string – Crazenezz 2012-04-16 08:50:06

回答

9

这样的问题是什么的正则表达式作了为:前 “HTTP” 有

  • \b

    Pattern findUrl = Pattern.compile("\\bhttp.*?\\.pdf\\b"); 
    Matcher matcher = findUrl.matcher("This is a URL http://www.google.com/MyDoc.pdf which should be used"); 
    while (matcher.find()) { 
        System.out.println(matcher.group()); 
    } 
    

    正则表达式解释是一个字边界(即xhttp不匹配)

  • http字符串“HTTP”(注意,这也符合“HTTPS”和“httpsomething”)
  • .*?任何字符(.)任意次数(*),但尝试使用的最少字符数量(?
  • \.pdf文字字符串“.pdf”
  • \b“.pdf”后面有一个单词边界(即.pdfoo不匹配)

如果你想只匹配http和https,尝试在你的字符串使用这个代替http

  • https?\: - 这串HTTP,那么匹配可选的“s”(在s之后由?指示),然后是冒号。
+0

非常感谢..这真的有所帮助...因为之前的文本可以是任何东西,所以这个提取URL的正则表达式是我所需要的。 – 2012-04-16 09:06:20

+0

如果你想支持任意的URL或字符串,看起来像URL但没有协议处理程序(例如www.foo.com),然后使用Gruber的正则表达式http://daringfireball.net/2010/ 07/improved_regex_for_matching_urls – 2012-04-16 09:13:35

1

你为什么不使用startsWith( “HTTP://”)( “PDF”)的endsWith String类的 mthods。

两个方法返回布尔值,如果两个返回,那么你成功的条件否则你的条件失败。

+0

该问题指出,他有一个字符串,其中包含“这是一个URL”应该使用的URL“。我没有看到'startsWith()'和'endsWith()'在这里适用。 – 2017-03-19 06:13:19

1

试试这个

String StringName="This is a URL http://www.google.com/MyDoc.pdf which should be used"; 

StringName=StringName.substring(StringName.indexOf("http:"),StringName.indexOf("which")); 
1

您可以在这里使用Regular Expression电源。 首先你必须找到原始字符串Url然后删除其他部分。

下面的代码显示我的建议:

String regex = "\\b(http|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]"; 
    String str = "This is a URL http://www.google.com/MyDoc.pdf which should be used"; 

    String[] splited = str.split(regex); 

    for(String current_part : splited) 
    { 
     str = str.replace(current_part, ""); 
    } 

    System.out.println(str); 

此代码片段罐检索任何网址与任何模式的任意字符串。 你不能在上面的正则表达式中添加自定义协议,如https协议部分。

我希望我的回答可以帮助您;)

+0

请注意,此模式不符合国际化域名,例如http://مثال.إختبار – 2012-04-17 11:42:55

0
public static String getStringBetweenStrings(String aString, String aPattern1, String aPattern2) { 
    String ret = null; 
    int pos1,pos2; 

    pos1 = aString.indexOf(aPattern1) + aPattern1.length(); 
    pos2 = aString.indexOf(aPattern2); 

    if ((pos1>0) && (pos2>0) && (pos2 > pos1)) { 
     return aString.substring(pos1, pos2); 
    } 

    return ret; 
}