Just My Life & My Work

我們時常有個需求,就是去判斷數字與字母的規則,比如身份證字號是一個大寫字母+九個數字。判斷方法有很多種,這裡有個非常方便的技巧,就是使用正規表達式 (Regular Expression)

我可以這麼寫⋯⋯

/**
 Theme: Regular Expression
 IDE: Xcode 7
 Language: Objective C
 Date: 105/03/05
 Author: HappyMan
 Blog: https://cg2010studio.wordpress.com/
 */
    NSString *errorMessage;
    // 確認身分證字號格式
    NSString *phoneNumber = @“L123456789";
    NSString *phoneRegex = @"[A-Z][0-9]{9}";
    NSPredicate *test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
    BOOL matches = [test evaluateWithObject:phoneNumber];
    if (!matches) {
        errorMessage = @"身份證字號第一碼英文+後9碼為數字";
    }

看了以上的程式片段,就知道如何使用了吧!

那其實正規表達式還有很多種用法,就拿StackOverFlow高人指點的例子⋯⋯

How to validate a phone number (NSString *) in objective-c? Rules:

  • minimum 7 digits
  • maximum 10 digits
  • the first digit must be 2, 3, 5, 6, 8 or 9

實作解答如下:

NSString *phoneNumber = ...;
NSString *phoneRegex = @"[235689][0-9]{6}([0-9]{3})?";
NSPredicate *test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
BOOL matches = [test evaluateWithObject:phoneNumber];

參考:Objective-c regex to check phone number

隨意留個言吧:)~

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料

標籤雲