2016-02-02 3 views
0

Je laisse un utilisateur entrer son adresse et j'ai besoin d'en extraire le code postal.Extrait du code postal à 5 ​​chiffres de la chaîne

J'ai trouvé que ce RegEx devrait fonctionner: \d{5}([ \-]\d{4})? mais j'ai du mal à le faire fonctionner sur Swift.

C'est là que je "m à:

private func sanatizeZipCodeString() -> String { 
     let retVal = self.drugNameTextField.text 

     let regEx = try! NSRegularExpression(pattern: "", options: .CaseInsensitive) 

     let match = regEx.matchesInString(retVal!, options: [], range: NSMakeRange(0, (retVal?.characters.count)!)) 

     for zip in match { 
      let matchRange = zip.range 

     } 
    } 

Je ne comprends pas pourquoi je ne peux pas tirer la première chaîne correspondant à

Répondre

2

Vous pouvez essayer cela

func match() { 
    do { 
     let regex = try NSRegularExpression(pattern: "\\b\\d{5}(?:[ -]\\d{4})?\\b", options: []) 
     let retVal = "75463 72639823764 gfejwfh56873 89765" 
     let str = retVal as NSString 
     let postcodes = regex.matchesInString(retVal, 
     options: [], range: NSMakeRange(0, retVal.characters.count)) 
     let postcodesArr = postcodes.map { str.substringWithRange($0.range)} 
     // postcodesArr[0] will give you first postcode 
    } catch let error as NSError { 

    } 
} 
0

Vous pouvez utiliser

"\\b\\d{5}(?:[ -]\\d{4})?\\b" 

Les limites de mots s'assurent que vous ne correspondez qu'à un mot entier ZIP

Les barres obliques inverses doivent être doublées

Le trait d'union à la fin de la classe de caractères n'a pas besoin d'être échappé.

Pour l'utiliser:

func regMatchGroup(regex: String, text: String) -> [[String]] { 
do { 
    var resultsFinal = [[String]]() 
    let regex = try NSRegularExpression(pattern: regex, options: []) 
    let nsString = text as NSString 
    let results = regex.matchesInString(text, 
     options: [], range: NSMakeRange(0, nsString.length)) 
    for result in results { 
     var internalString = [String]() 
     for var i = 0; i < result.numberOfRanges; ++i{ 
      internalString.append(nsString.substringWithRange(result.rangeAtIndex(i))) 
     } 
     resultsFinal.append(internalString) 
    } 
    return resultsFinal 
    } catch let error as NSError { 
     print("invalid regex: \(error.localizedDescription)") 
     return [[]] 
    } 
} 

let input = "75463 72639823764 gfejwfh56873 89765" 
let matches = regMatchGroup("\\b\\d{5}(?:[ -]\\d{4})?\\b", text: input) 
if (matches.count > 0) 
{ 
    print(matches[0][0]) // Print the first one 
}