Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift regex - How to extract a matching group

Tags:

regex

swift

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

like image 967
Jeef Avatar asked Dec 15 '22 19:12

Jeef


1 Answers

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.

like image 159
MirekE Avatar answered Jan 01 '23 20:01

MirekE