Regular expression to find URLs within a string

前端 未结 27 2094
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 14:18

Does anyone know of a regular expression I could use to find URLs within a string? I\'ve found a lot of regular expressions on Google for determining if an entire string is

27条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 14:55

    None of the solutions provided here solved the problems/use-cases I had.

    What I have provided here, is the best I have found/made so far. I will update it when I find new edge-cases that it doesn't handle.

    \b
      #Word cannot begin with special characters
      (?\w{2,10}:\/\/)?
      #Domains have to be of a length of 1 chars or greater
      ((?:\w|\&\#\d{1,5};)[.-]?)+
      #The domain ending has to be between 2 to 15 characters
      (\.([a-z]{2,15})
           #If no domain ending we want a port, only if a protocol is specified
           |(?(protocol)(?:\:\d{1,6})|(?!)))
    \b
    #Word cannot end with @ (made to catch emails)
    (?![@])
    #We accept any number of slugs, given we have a char after the slash
    (\/)?
    #If we have endings like ?=fds include the ending
    (?:([\w\d\?\-=#:%@&.;])+(?:\/(?:([\w\d\?\-=#:%@&;.])+))*)?
    #The last char cannot be one of these symbols .,?!,- exclude these
    (?

提交回复
热议问题