Created
November 24, 2014 15:34
-
-
Save nisshiee/061a37b0e5c85aa92176 to your computer and use it in GitHub Desktop.
とりあえず書き殴ってみた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
import Foundation | |
class Regex { | |
let internalExpression: NSRegularExpression | |
let pattern: String | |
init(_ pattern: String) { | |
self.pattern = pattern | |
var error: NSError? | |
self.internalExpression = NSRegularExpression(pattern: pattern, options: nil, error: &error)! | |
} | |
func matches(input: String) -> Bool { | |
let matches = self.internalExpression.matchesInString(input, options: nil, range:NSMakeRange(0, countElements(input))) | |
return matches.count > 0 | |
} | |
func groups(input: String) -> [String]? { | |
let matches = self.internalExpression.matchesInString(input, options: nil, range:NSMakeRange(0, countElements(input))) | |
if matches.count > 0 { | |
var result: [String] = [] | |
for i in 0 ..< matches.count { | |
let nsrange: NSRange = (matches[i] as NSTextCheckingResult).range | |
let nsstring: NSString = input as NSString | |
let group: String = nsstring.substringWithRange(nsrange) | |
result.append(group) | |
} | |
return result | |
} else { | |
return nil | |
} | |
} | |
} |
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
import Foundation | |
infix operator =~ { associativity left precedence 130 } | |
func =~ (input: String, pattern: String) -> Bool { | |
return Regex(pattern).matches(input) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment