Deco Deco - 1 year ago 56
Swift Question

Can I stop my capture group from being overwritten?

I'm trying to capture the first delimiter used within a phone number in order to identify what's used as a numbers internal delimiter and what's used to separate two numbers.

Right now I can identify the last delimiter. It appears the capture group is overwritten each time a new value is picked up. Is there anyway of retaining what is first captured using a flag or a specific swift method?


(?:\\d([\\-\\. ])?){7,15}

Swift Method

func regexParse(pattern:String, captureGroup:Int, caseSensitive:Bool) ->[String]
//Creates empty results array.
var resultsArray = [String]()

//Sets Case sensitivity
var caseSensitivity = NSRegularExpressionOptions.CaseInsensitive
caseSensitivity = NSRegularExpressionOptions.init(rawValue: 0)

//Sets regex to correct pattern
let regex = try NSRegularExpression(pattern: pattern, options: caseSensitivity)
//Converts string to NSString as swift doesn't support regex
let nsString = self as NSString

//Sets parsing range to the entire string
let all = NSMakeRange(0, nsString.length)

//Enumerates through all matches and extracts the 1st capture bracket for each match and adds it to the resultsArray.

regex.enumerateMatchesInString(self, options: NSMatchingOptions(rawValue: 0), range: all) { (result: NSTextCheckingResult?, _, _) in
let capturedRange = result!.rangeAtIndex(captureGroup)
if !NSEqualRanges(capturedRange, NSMakeRange(NSNotFound, 0))
let theResult = nsString.substringWithRange(capturedRange)
return resultsArray

print("Invalid regex")
return(["Error"]) //Maybe refactor this for something that's impossible to be a valid result

Answer Source

You need to use this regex:

\d+([-. ])[-.\d]*

To get the delimiter, which will be in the capturing group

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download