Created
May 2, 2015 21:21
-
-
Save aarti/a082df06217c6caff749 to your computer and use it in GitHub Desktop.
Swift extensions for String
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
extension String { | |
func scan(regex : String) -> [String] { | |
let regex = NSRegularExpression(pattern: regex, | |
options: nil, error: nil)! | |
let nsString = self as NSString | |
let results = regex.matchesInString(nsString as String, | |
options: nil, range: NSMakeRange(0, nsString.length)) | |
as! [NSTextCheckingResult] | |
return map(results) { nsString.substringWithRange($0.range)} | |
} | |
subscript (i: Int) -> Character { | |
return self[advance(self.startIndex, i)] | |
} | |
subscript (i: Int) -> String { | |
return String(self[i] as Character) | |
} | |
subscript (r: Range<Int>) -> String { | |
return substringWithRange(Range(start: advance(startIndex, r.startIndex), end: advance(startIndex, r.endIndex))) | |
} | |
} | |
let number = "(123) (456) 7890" | |
let wordArr = number.scan("\\w+") | |
println(wordArr) // [123, 456, 7890] | |
let digitsOnly = "".join(wordArr) | |
println(digitsOnly) // 1234567890 | |
"abcde"[0] === "a" | |
"abcde"[0...2] === "abc" | |
"abcde"[2..<4] === "cd" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment