2016-02-02 82 views
0

我讓用戶輸入他們的地址,我需要從中提取郵政編碼。從字符串中提取5位數的郵政編碼

我發現這個正則表達式應該可以工作:\d{5}([ \-]\d{4})?但是我很難讓這個工作在Swift上。

這就是我「米在:

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 

     } 
    } 

我不明白爲什麼我不能只拉第一個匹配串出

回答

2

你可以試試這個出

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

您可以使用

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

字邊界確保您只匹配整個單詞ZIP。

反斜槓必須翻倍

字符類末尾的連字符不必轉義。

要使用它:

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 
} 
相關問題