This is a question about Regular Expressions in Swift. I have found various tutorials that mention how to do searching and matching but nothing about grouping:
Here is a simple Match statement:
if Regex("\\w{4}").test("ABCD") {
println("matches pattern")
}
But what if i wanted to extract the 3rd letter:
if Regex("\\w{2}(\\w)\\w").text("REGX") {
print("Found a match with \$1")
}
What is the correct syntax to print matching groups?
Or more specifically - how would I extract 2044 from 2014-10-29T20:44:00
You can use NSRegularExpression
.
var pattern = ".+T(\\d\\d):(\\d\\d).+"
var string = "2014-10-29T20:44:00"
var error: NSError? = nil
var regex = NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.DotMatchesLineSeparators, error: &error)
var result = regex?.stringByReplacingMatchesInString(string, options: nil, range: NSRange(location:0,
length:countElements(string)), withTemplate: "$1$2")
I would be inclined to do this without regular expressions, though:
var charSet = NSCharacterSet(charactersInString: "T:")
var array =
string.componentsSeparatedByCharactersInSet(charSet)
var result2 =
"\(array[1])\(array[2])"
This breaks the datetime string to array of substrings separated by either T or : and I get the hours and minutes in second and third element of the returned array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With