import Foundation
let pattern = #"(?:(href|src).+?[\w\-\s]{30,}")"#
let regex = try! NSRegularExpression(pattern: pattern)
let testString = #"""
What I'm looking to do:
Regex should only confirm a match if it identifies at least 4 URLs with long strings. My current pattern is:
/(?:(href|src).+?[\w\-\s]{30,}")/g
This pattern detects all six matches shown below, but even if only one match was present it would still return that match. I want it to return "no match" if there aren't at least 4 present, and note that since each URL has a DIFFERENT long string, I can't use {4,}? as it only works if it finds 4 instances of the same thing.
___MATCH ONE___
<body><a href="http://keyslinte.us/ayMxQdN567OeuL6MbKxQ4MtGvL-TLr_DqZJs3ZP1eFs"><img border="0"
___MATCH TWO___
src="http://keyslinte.us/UHJo_e_vTeHGuwu-U-fdLOl_c0KUCZEG2TEDKCTVjg"
___MATCH THREE___
<p align="left"><a href="http://keyslinte.us/LO0GUD
U9uxlR7CyPiNBIWLf3dU0eWVZ872lF8Gus8Q"><img
___MATCH FOUR___
href="http://keyslinte.us/LO0GUDU9uxlR7CyPiNBIWLf3dU0eWVZ872lF8Gus8Q"
___MATCH FIVE___
href="http://keyslinte.us/EkpR4EpSAdBmRvPT32X8bgQW2ywXo3XnK5-xIIe3vA"
___MATCH SIX___
<p align="left"><a href="http://keyslinte.us/B-OPTRjhR6t388ah5NMUHoSPAjN1LENnJRoEurIXIQ"><img
"""#
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