Created
April 4, 2022 21:24
-
-
Save nahuelDeveloper/0dd7d18bf090e75ac95b87804e313c1e to your computer and use it in GitHub Desktop.
Simple Regex Checker in Swift
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
class RegexManager { | |
var regex: NSRegularExpression | |
init?(regexPattern: String) { | |
do { | |
regex = try NSRegularExpression(pattern: regexPattern) | |
} catch { | |
// Invalid pattern | |
return nil | |
} | |
} | |
func checkIfTextMatchesRegex(textToCheck: String) -> Bool { | |
let textToCheckRange = NSRange(location: 0, length: textToCheck.utf16.count) | |
return regex.firstMatch(in: textToCheck, | |
options: [], | |
range: textToCheckRange) != nil | |
} | |
} | |
// Regex pattern | |
let regexPattern = "[a-z]at" | |
// Regex test Strings | |
let testString = "hat" | |
let testString2 = "pants" | |
let regexManager = RegexManager(regexPattern: regexPattern) | |
regexManager?.checkIfTextMatchesRegex(textToCheck: testString) | |
regexManager?.checkIfTextMatchesRegex(textToCheck: testString2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Inspired after reading this great article https://www.hackingwithswift.com/articles/108/how-to-use-regular-expressions-in-swift