Skip to content

Instantly share code, notes, and snippets.

@T-Pham T-Pham/test.swift
Last active Sep 3, 2018

Embed
What would you like to do?
url regex :(
import Foundation
let qqq = "https://yahoo.com/:;(&;&:93@;&:&&:'’'"
NSURL(string: qqq)
let tests = [
("google.com", true),
("www.google.com", true),
("http://google.com", true),
("http://www.google.com", true),
("https://google.com", true),
("https://www.google.com", true),
("google.co", true),
("www.google", false),
("google.c", false),
("www.google.c", false),
("http://google.c", false),
("http://www.google", false),
("http://www.google.c", false),
("http://b", false),
("abc.com", true),
("a-google.com", true),
("www.goog", false),
("http://www.goog", false),
("Google.com", true),
("a google.com", true),
("a https://b", false),
("google.com b", true),
("https://b b", false),
("a google.com b", true),
("a https://b b", false),
]
let regexString = "(^|\\W)((http:\\/\\/|https:\\/\\/)?([w|W]{3}.)?(?![w|W]{3}.)[a-zA-Z0-9]+([\\-\\.]{1}[a-zA-Z0-9]+)*\\.[a-zA-Z]{2,5}(:[0-9]{1,5})?(\\/[[A-Za-z0-9-\\._~:/\\?#\\[\\]@!\\$&'\\(\\)\\*\\+,;=]]*)?)($|(?=\\W))"
let regex = try! NSRegularExpression(pattern: regexString, options: [])
tests.filter { (urlString, expectedResult) in
let matches = regex.matches(in: urlString, options: [], range: NSRange(location: 0, length: (urlString as NSString).length))
let ok = (matches.count > 0 && matches.first!.numberOfRanges > 2) == expectedResult
if !ok {
print(urlString)
}
return !ok
}.count
let string = "a https://google.com/abc?a=b&c=d#abc’def b"
regex.matches(in: string, options: [], range: NSRange(location: 0, length: (string as NSString).length)).first!.range(at: 2).length == "https://google.com/abc?a=b&c=d#abc".utf16.count
let string2 = "a https://yahoo.com/:;(&;&:93@;&:&&:’a b"
regex.matches(in: string2, options: [], range: NSRange(location: 0, length: (string2 as NSString).length)).first!.range(at: 2).length == "https://yahoo.com/:;(&;&:93@;&:&&:".utf16.count
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.