Regular expression to find URLs within a string

前端 未结 27 1767
被撕碎了的回忆
被撕碎了的回忆 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:57

    This is the best one.

    NSString *urlRegex="(http|ftp|https|www|gopher|telnet|file)(://|.)([\\w_-]+(?:(?:\\.[\\w_-]+)‌​+))([\\w.,@?^=%&:/~+#-]*[\\w@?^=%&/~+#-])?";
    
    0 讨论(0)
  • 2020-11-22 14:58

    This is the one I use

    (http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?
    

    Works for me, should work for you too.

    0 讨论(0)
  • 2020-11-22 14:59

    Wrote one up myself:

    let regex = /([\w+]+\:\/\/)?([\w\d-]+\.)*[\w-]+[\.\:]\w+([\/\?\=\&\#]?[\w-]+)*\/?/gm
    

    It works on ALL of the following domains:

    https://www.facebook.com
    https://app-1.number123.com
    http://facebook.com
    ftp://facebook.com
    http://localhost:3000
    localhost:3000/
    unitedkingdomurl.co.uk
    this.is.a.url.com/its/still=going?wow
    shop.facebook.org
    app.number123.com
    app1.number123.com
    app-1.numbEr123.com
    app.dashes-dash.com
    www.facebook.com
    facebook.com
    fb.com/hello_123
    fb.com/hel-lo
    fb.com/hello/goodbye
    fb.com/hello/goodbye?okay
    fb.com/hello/goodbye?okay=alright
    Hello www.google.com World http://yahoo.com
    https://www.google.com.tr/admin/subPage?qs1=sss1&qs2=sss2&qs3=sss3#Services
    https://google.com.tr/test/subPage?qs1=sss1&qs2=sss2&qs3=sss3#Services
    http://google.com/test/subPage?qs1=sss1&qs2=sss2&qs3=sss3#Services
    ftp://google.com/test/subPage?qs1=sss1&qs2=sss2&qs3=sss3#Services
    www.google.com.tr/test/subPage?qs1=sss1&qs2=sss2&qs3=sss3#Services
    www.google.com/test/subPage?qs1=sss1&qs2=sss2&qs3=sss3#Services
    drive.google.com/test/subPage?qs1=sss1&qs2=sss2&qs3=sss3#Services
    https://www.example.pl
    http://www.example.com
    www.example.pl
    example.com
    http://blog.example.com
    http://www.example.com/product
    http://www.example.com/products?id=1&page=2
    http://www.example.com#up
    http://255.255.255.255
    255.255.255.255
    

    You can see how it performs here on regex101 and adjust as needed

    0 讨论(0)
提交回复
热议问题