2013-05-01 24 views
2

我解析文本Sscala和使用正則表達式:正則表達式,HTTP鏈接未URL圖像

val imageLink = "(http?:\\/\\/.*\\.(?:png|jpg|gif|bmp|jpeg))".r.findAllIn(postText).toList 
val htmlLink = "http(s)?://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?" 
      .r.findAllIn(postText).toList.filterNot(s => s.contains("jpg") || s.contains("jpeg") 
       || s.contains("png") || s.contains("gif") || s.contains("bmp")) 

但我不想使用所有這些s.contains。我想在正則表達式中找到不會結束jpg,bmp等的http鏈接。

感謝

回答

4

的想法是使用負前瞻(?!)表達式:

"(?!.*(?:jpg|jpeg|png|gif|bmp))http(s)?://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?" 

您也可以省略括號http(s)? - >https?因爲?將只在兩種情況下s字符工作。

正則表達式的進一步改進將檢查擴展的確切位置,它可能出現在URL中。