Last active
February 18, 2016 14:28
-
-
Save to4iki/aef9020ad7911ed02737 to your computer and use it in GitHub Desktop.
regex =~ operator for Swift
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
import Foundation | |
/// See also | |
/// - https://github.com/kasei/SwiftRegex | |
struct Regex { | |
private let pattern: String | |
private let internalRegexp: NSRegularExpression | |
init(_ pattern: String) { | |
self.pattern = pattern | |
self.internalRegexp = try! NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.CaseInsensitive) | |
} | |
func isMatch(input: String) -> Bool { | |
return matches(input).count > 0 | |
} | |
func matches(input: String) -> [String] { | |
let matches = internalRegexp.matchesInString(input, options: [], range: NSMakeRange(0, input.characters.count)) | |
return matches.reduce([]) { (acc, m) -> [String] in | |
acc + [(input as NSString).substringWithRange(m.range)] | |
} | |
} | |
} | |
infix operator =~ {} | |
func =~ (input: String, pattern: String) -> [String] { | |
return Regex(pattern).matches(input) | |
} |
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
let pattern = "http://([a-zA-Z0-9]|.)+" | |
let str = "銘柄コード:1557,銘柄名:SPDR S&P500 ETF TRUST板価格:25270.0,板数量:10000にいびつな板(寄与率:81.20178%)を検出しました。http://oreore.com/servlets/Action?SRC=1234" | |
Regex(pattern).isMatch(str) //=> true | |
(str =~ pattern).first //=> http以下を取得 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment