import Foundation
let pattern = #"""
(?s:
<ins
(?:(?!</ins>).)*?
"adsbygoogle"
.*?
</ins>)
"""#
let regex = try! NSRegularExpression(pattern: pattern, options: .allowCommentsAndWhitespace)
let testString = #"""
0
down vote
favorite
I have a thousand html pages (without admin panel) with codes of adsense. And I want to remove all of them from html. One code looks like:
<ins class="adsbygoogle"
style="display:inline-block;width:160px;height:600px"
data-ad-client="ca-pub-7165746718333100"
data-ad-slot="9087512399"></ins>
Another:
<ins class="adsbygoogle"
style="display:inline-block;width:160px;height:600px"
data-ad-client="ca-pub-7163746711373100"
data-ad-slot="7467236139"></ins>
All of them are similar but not equal. A tried to write regex to find and replace it with empty string, but unsuccessfully.
Any suggetion how to do it automatically?
"""#
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