Created
October 2, 2015 02:35
-
-
Save jaisonv/0f33f4f83c951e443807 to your computer and use it in GitHub Desktop.
Working with regex in 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
let text = "Text to get the match" | |
let regex = NSRegularExpression(pattern: "([^ ]+)", options: nil, error: nil)! | |
let matches = regex.matchesInString(text, options: nil, range: NSRange(location: 0, length: count(text))) | |
var substring = "" | |
for match in matches as! [NSTextCheckingResult] { | |
// range at index 0 returns the full match | |
// range at index 1 returns the first capture group | |
// range at index 2 returns the second capture group and so on... | |
substring = (text as NSString).substringWithRange(match.rangeAtIndex(1)) | |
} | |
println(substring) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment