import Foundation
let pattern = #"<a[^>]*?href=(?|"([^"]*?)"|'([^']*?)').*?>(.*?)<\/a>"#
let regex = try! NSRegularExpression(pattern: pattern, options: [.caseInsensitive, .dotMatchesLineSeparators])
let testString = ##"""
# Basic Cases
<a href="http://test.com">double quotes</a>
<a href='http://test.com'>single quotes</a>
<a class="blah a href" data="blah" href="#rel-link" rel=''>complicated attributes</a>
<a href="#anchor-1">adjacent</a><a href="#anchor-2">anchors</a>
# Extra Cases
<a href="http://test.com">title
linebreak</a>
<a href="#anchor-reference"><span>inline span</span></a>
<ahref="uri:test-uri">technically invalid anchor</a>
<a href="http://test.com"><a href="#invalid">technically invalid internal anchor</a></a>
<a href="'''''\"\"">quotes test</a>
# Random Junk Stress Tests
<a class="" href=""rergerger er erg><></><>.e.ewfe></wef/we. ></a>Test</a>
<ahref="e">e</a>
<a>e</a>
<a href="">e<a href="">e</a></a>
"""##
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