Skip to content

Instantly share code, notes, and snippets.

@jaisonv
Created October 2, 2015 02:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaisonv/0f33f4f83c951e443807 to your computer and use it in GitHub Desktop.
Save jaisonv/0f33f4f83c951e443807 to your computer and use it in GitHub Desktop.
Working with regex in Swift
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