Skip to content

Instantly share code, notes, and snippets.

@vibrazy
Created March 20, 2016 11:30
Show Gist options
  • Select an option

  • Save vibrazy/ec4f0e4a0c5e5ecac5fb to your computer and use it in GitHub Desktop.

Select an option

Save vibrazy/ec4f0e4a0c5e5ecac5fb to your computer and use it in GitHub Desktop.
Validate UK Postcodes in Swift 2.0
//
// UKPostcodeValidator.swift
// Medio
//
// Created by Daniel Tavares on 20/03/2016.
// Copyright © 2016 Daniel Tavares. All rights reserved.
// References: http://stackoverflow.com/questions/164979/uk-postcode-regex-comprehensive
// References: http://benscheirman.com/2014/06/regex-in-swift/
// Usage: UKPostcodeValidator.validate("W1D 5LH")
//
import Foundation
private class Regex {
let internalExpression: NSRegularExpression
let pattern: String
init(_ pattern: String) {
self.pattern = pattern
self.internalExpression = try! NSRegularExpression(pattern: pattern, options: .CaseInsensitive)
}
func test(input: String) -> Bool {
let matches = self.internalExpression.matchesInString(input, options: NSMatchingOptions.Anchored, range: NSMakeRange(0, input.characters.count))
return matches.count > 0
}
}
struct UKPostcodeValidator {
static let pattern = "^(GIR 0AA)|((([A-Z][0-9]{1,2})|(([A-Z][A-HJ-Y][0-9]{1,2})|(([A-Z][0-9][A-Z])|([A-Z][A-HJ-Y][0-9]?[A-Z])))) [0-9][A-Z]{2})$"
static func validate(input: String) -> Bool {
return Regex(pattern).test(input)
}
}
@Jimmybee

Copy link
Copy Markdown

But otherwise very handy, thanks

@Nedunchezhian

Nedunchezhian commented Sep 10, 2019

Copy link
Copy Markdown

How to use \s? to allow for no whitespace IN SWIFT4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment