0

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?

Regex

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

Swift Method

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

        //Sets Case sensitivity
        var caseSensitivity = NSRegularExpressionOptions.CaseInsensitive
        if(caseSensitive)
        {
            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)
                resultsArray.append(theResult)
            }
        }
        return resultsArray

    }
    catch
    {
        print("Invalid regex")
        return(["Error"]) //Maybe refactor this for something that's impossible to be a valid result
    }
}
Laurel
  • 5,965
  • 14
  • 31
  • 57
Declan McKenna
  • 4,321
  • 6
  • 54
  • 72

1 Answers1

1

You need to use this regex:

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

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

Declan McKenna
  • 4,321
  • 6
  • 54
  • 72
Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142