我让用户输入他们的地址,我需要从中提取邮政编码。
我发现这个RegEx应该可以工作:\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
}
}
我不明白为什么我不能把第一个匹配的字符串拉出来!
答案 0 :(得分: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 {
}
}
答案 1 :(得分: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
}