Last active
May 7, 2016 06:38
-
-
Save kazuhiro4949/c77352ea0698b13d3a2f2f7ea2a78011 to your computer and use it in GitHub Desktop.
Swift Regex wrapper snippet. ( supporting version 2.0+ )
This file contains 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
/** | |
#### Example | |
if case Regex("^regular\s.+$") = "regular expression" { | |
return true | |
} | |
switch "regular expression" { | |
case Regex("^regular\s.+$"): | |
print("match ^regular\s.+$") | |
case Regex("^regurar\s.+$"): | |
print("match ^regurar\s.+$") | |
default: | |
print("no match") | |
} | |
*/ | |
func ~= (pattern: Regex, value: String) -> Bool { | |
return pattern.test(value) | |
} | |
/** | |
#### Example | |
wrapper class for NSRegularExpression | |
``` | |
let regex = Regex("^regular\s.+$") | |
let isMatch = regex.test("regular expression") | |
print(isMtch) | |
``` | |
*/ | |
class Regex { | |
let internalExpression: NSRegularExpression | |
let pattern: String | |
init(_ pattern: String) { | |
self.pattern = pattern | |
let result = try? NSRegularExpression(pattern: pattern, options: [.CaseInsensitive, .DotMatchesLineSeparators, .AnchorsMatchLines]) | |
self.internalExpression = result ?? NSRegularExpression() | |
} | |
/** | |
If an input string matches the pattern, return true, otherwise return false. | |
- parameter input:String | |
- returns: Bool | |
*/ | |
func test(input: String) -> Bool { | |
let matches = self.internalExpression.matchesInString(input, options: [], range:NSMakeRange(0, input.characters.count)) | |
return matches.count > 0 | |
} | |
/** | |
If an input string matches the pattern, return matched strings, otherwise return nil. | |
- parameter input:String | |
- returns: [String]? | |
*/ | |
func matches(input: String) -> [String]? { | |
if self.test(input) { | |
let nsString = input as NSString | |
let matches = self.internalExpression.matchesInString(input, options: [], range:NSMakeRange(0, nsString.length) ) | |
var results: [String] = [] | |
for i in 0 ..< matches.count { | |
results.append( (input as NSString).substringWithRange(matches[i].range) ) | |
} | |
return results | |
} | |
return nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment