import Foundation
let pattern = #"((?<=[^a-zA-Z0-9])(?:https?\:\/\/|[a-zA-Z0-9]{1,}\.{1}|\b)(?:\w{1,}\.{1}){1,5}(?:com|org|edu|gov|uk|net|ca|de|jp|fr|au|us|ru|ch|it|nl|se|no|es|mil|iq|io|ac|ly|sm){1}(?:\/[a-zA-Z0-9]{1,})*)"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
== Good ==
https://facebook.com/marko/polo
https://facebook.com/marko/pol2o
www.moshe.io
http://marko.polo.com
subdomain.pizza.com
bitly.com/14awOx4
== Good in random text
Dude, I'm telling you, every other https://facebook.com/marko/polo URL regex just so sucked. it even crashed https://facebook.com/marko/pol2o. In one case + there are case where www.moshe.io would be cought but this one works likes charm http://marko.polo.com exactly what I needed // // look it doesn't catch subdomain.pizza.com anyhthing else ! it's totally amazing !
bitly.com/fdsafdf
== Bad ==
https://www.........more..........no/com
4.5x10.9
etc..!
me.you
you.them
"""#
let stringRange = NSRange(location: 0, length: testString.utf16.count)
let matches = regex.matches(in: testString, range: stringRange)
var result: [[String]] = []
for match in matches {
var groups: [String] = []
for rangeIndex in 1 ..< match.numberOfRanges {
let nsRange = match.range(at: rangeIndex)
guard !NSEqualRanges(nsRange, NSMakeRange(NSNotFound, 0)) else { continue }
let string = (testString as NSString).substring(with: nsRange)
groups.append(string)
}
if !groups.isEmpty {
result.append(groups)
}
}
print(result)
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Swift 5.2, please visit: https://developer.apple.com/documentation/foundation/nsregularexpression