Tutorial by Examples

extension String { func matchesPattern(pattern: String) -> Bool { do { let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions(rawValue: 0)) let range: NSRange = NSMakeRange(...
There are several considerations when implementing Regular Expressions in Swift. let letters = "abcdefg" let pattern = "[a,b,c]" let regEx = try NSRegularExpression(pattern: pattern, options: []) let nsString = letters as NSString let matches = regEx.matches(in: letters, opt...
Patterns can be used to replace part of an input string. The example below replaces the cent symbol with the dollar symbol. var money = "¢¥€£$¥€£¢" let pattern = "¢" do { let regEx = try NSRegularExpression (pattern: pattern, options: []) let nsString = money as NSS...
To match special characters Double Backslash should be used \. becomes \\. Characters you'll have to escape include (){}[]/\+*$>.|^? The below example get three kinds of opening brackets let specials = "(){}[]" let pattern = "(\\(|\\{|\\[)" do { let regEx = try N...
Regular expressions can be used to validate inputs by counting the number of matches. var validDate = false let numbers = "35/12/2016" let usPattern = "^(0[1-9]|1[012])[-/.](0[1-9]|[12][0-9]|3[01])[-/.](19|20)\\d\\d$" let ukPattern = "^(0[1-9]|[12][0-9]|3[01])[-/](0[1...
func isValidEmail(email: String) -> Bool { let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}" let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx) return emailTest.evaluate(with: email) } or you could use String extensio...

Page 1 of 1