Extract 5 digit zip code from string

吃可爱长大的小学妹 提交于 2019-12-12 03:25:54

问题


I'm letting a user enter their address and I need to extract the zip code from it.

I found that this RegEx should work: \d{5}([ \-]\d{4})? however I'm having an extremely difficult time getting this to work on Swift.

This is where I"m at:

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

        }
    }

I don't understand why I can't just pull the first matching string out!


回答1:


You can try this out

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 {

    }
}   



回答2:


You can use

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

Word boundaries make sure you only match a whole word ZIP.

Backslashes must be doubled.

The hyphen at the end of the character class does not have to be escaped.

To use it:

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
}


来源:https://stackoverflow.com/questions/35162104/extract-5-digit-zip-code-from-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!