Created
February 27, 2020 13:29
-
-
Save bill1m/29a64250eadb8894625883e98f81b9d1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: These Swift examples follow the Objective-C found in [NSRegularExpression](https://developer.apple.com/documentation/foundation/nsregularexpression) | |
import Foundation | |
let regex1 = try! NSRegularExpression(pattern: "\\b(a|b)(c|d)\\b", options: [.caseInsensitive]) | |
let string1 = "Test with Ad and ad and Ac and AC and bD and bd and Bc and BC in the string." | |
let range1 = NSMakeRange(0, string1.count) | |
let numberOfMatches = regex1.numberOfMatches(in: string1, range: range1) | |
let firstRange = regex1.rangeOfFirstMatch(in: string1, range: range1) | |
let matchResults = regex1.matches(in: string1, range: range1) | |
for (index, matchResult) in matchResults.enumerated() { | |
print(index, matchResult.range, NSString(string: string1).substring(with: matchResult.range)) | |
} | |
let firstResult = regex1.firstMatch(in: string1, range: range1)! | |
print(firstResult.range, NSString(string: string1).substring(with: firstResult.range)) | |
regex1.enumerateMatches( | |
in: string1, options: [], range: range1, | |
using: { result, flags, stop | |
in | |
// The NSTextCheckingResult is always non-nil given options of []. | |
guard let result = result else { return } | |
print(result.range, NSString(string: string1).substring(with: result.range)) | |
}) | |
print(regex1.stringByReplacingMatches(in: string1, range: range1, withTemplate: "$2$1")) | |
let mutableString1 = NSMutableString(string: string1) | |
regex1.replaceMatches(in: mutableString1, range: range1, withTemplate: "$2$1") | |
print(mutableString1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment