Validated by a regular expression, pattern "^[0-9]+$" using the following method -validateString:withPattern:
[self validateString:"12345" withPattern:"^[0-9]+$"];
- If "123.123" is considered
- With the pattern
"^[0-9]+(.{1}[0-9]+)?$"
- If exactly 4 digits, without
"." ,- With the pattern
"^[0-9]{4}$" .
- If digits are digits without
"." and the length is from 2 to 5.- With the pattern
"^[0-9]{2,5}$" .
Regular expression can be checked on the online website .
The auxiliary function is as follows.
// Validate the input string with the given pattern and // return the result as a boolean - (BOOL)validateString:(NSString *)string withPattern:(NSString *)pattern { NSError *error = nil; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error]; NSAssert(regex, @"Unable to create regular expression"); NSRange textRange = NSMakeRange(0, string.length); NSRange matchRange = [regex rangeOfFirstMatchInString:string options:NSMatchingReportProgress range:textRange]; BOOL didValidate = NO; // Did we find a matching range if (matchRange.location != NSNotFound) didValidate = YES; return didValidate; }
Swift 3 version:
Test on the playground.
import UIKit import Foundation func validate(_ str: String, pattern: String) -> Bool { if let range = str.range(of: pattern, options: .regularExpression) { let result = str.substring(with: range) print(result) return true } return false } let a = validate("123", pattern: "^[0-9]+") print(a)
AechoLiu Feb 16 '16 at 7:19 2016-02-16 07:19
source share