问题
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