Created
January 26, 2023 15:22
-
-
Save DarrenHurst/90336a7c518ab399e1b17f7d08be8772 to your computer and use it in GitHub Desktop.
String Generics, Regexp and Interpolation
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
| // | |
| // StringGenerics.swift | |
| // | |
| // Created by Darren Hurst on 2023-01-26. | |
| // | |
| import Foundation | |
| extension String { | |
| // left hand side "This is a string xx" ~= regular expression | |
| func testRegString(){ | |
| // test string for trademark | |
| let invitation = "DarrenHurst_™" | |
| let fakeinvitation = "Darren_™" | |
| let tradeMark = #"\bDarrenHurst_?™?\b"# | |
| if invitation.contains("™") { | |
| let tradeMarkIndex = invitation.findIndex(of: "™", in: Array(invitation)) | |
| print("Has Trademark at index: \(tradeMarkIndex ?? 0)") | |
| } | |
| if (invitation ~= tradeMark) { | |
| print("DarrenHurst_ trademarkcheck passed") | |
| } else { | |
| print("DarrenHurst_ trademarkcheck failed") | |
| } | |
| if (fakeinvitation ~= tradeMark) { | |
| print("Not a fake") | |
| } else { | |
| print("Fake fake fake") | |
| } | |
| } | |
| static func ~= (lhs: String, rhs: String) -> Bool { | |
| guard let regex = try? NSRegularExpression(pattern: rhs) else { return false } | |
| let range = NSRange(location: 0, length: lhs.utf16.count) | |
| return regex.firstMatch(in: lhs, options: [], range: range) != nil | |
| } | |
| func findIndex<T: Equatable>(of valueToFind: T, in array:[T]) -> Int? { | |
| for (index, value) in array.enumerated() { | |
| if value == valueToFind { | |
| return index | |
| } | |
| } | |
| return nil | |
| } | |
| } | |
| extension NSRegularExpression { | |
| convenience init(_ pattern: String) { | |
| do { | |
| try self.init(pattern: pattern) | |
| } catch { | |
| preconditionFailure("Illegal regular expression: \(pattern).") | |
| } | |
| } | |
| } | |
| extension NSRegularExpression { | |
| func matches(_ string: String) -> Bool { | |
| let range = NSRange(location: 0, length: string.utf16.count) | |
| return firstMatch(in: string, options: [], range: range) != nil | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment