import Foundation
let pattern = #"^(?:(?:[_a-z0-9](?:[_a-z0-9-]{0,61}[a-z0-9])?|[0-9]{1,3}?/[0-9]{2})\.)+(?:[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?)?$"#
let regex = try! NSRegularExpression(pattern: pattern, options: [.anchorsMatchLines, .caseInsensitive])
let testString = #"""
This regexp can be used to validate domain names in Golang.
While it cannot enforce the 253 character limit (with optional trailing period not included)
that can be easily done with a `len(domain) <= 253` check.
This can be used as-is in other languages, even with RE2 regex engine.
Non-capturing groups are used.
Example validated domains (some may be invalid per TLD rules):
example.com
_25._tcp.SRV.example
a.punycoded-idna.xn--zckzah
under_score.example
0/27.0.0.1.in-addr.arpa
128/32.255.255.123.in-addr.arpa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.
Example invalid domains:
192.0.2.1
has spaces.com
easy,typo.example
23/1.invalid
domain\.escapes.invalid
trailing_.underscore.invalid
-leading.hyphens.invalid
trailing-.hyphens.invalid
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
TLDs have more validation, the following will not validate:
a
example
digit.1example
underscore._example_com
but with a trailing period, the same rules as non-TLD are applied:
a.
example.
digit.1example.
underscore._example_com.
"""#
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