iOS Regex

來源:互聯網
上載者:User

標籤:

在iOS開發中,正則一直是最常用的,但也是一直記不住的,現在做一些簡單的總結

我們在網上找的正則,要有‘\‘,這個在iOS是轉義符,需要‘\\‘這樣

int main(int argc, const char * argv[]) {    @autoreleasepool {        // insert code here...        // 1.建立Regex        // []:找到內部的某一個字串        // "[a-z]" :小寫        // "[a-zA-Z]" :大小寫        // "[a-zA-Z0-9]" :大小寫及數字        // "\\d" 相當於 "[0-9]"        // "\\d{3}" 相當於“\\d\\d\\d”,表示找到連續3個一起的數字        // "\\d{2,4}" 表示2數字或者4個數字 符合的。如"342455" ,得到兩個結果“3424“和”55”                // .    匹配除分行符號以外的任一字元        // \w    匹配字母或數字或底線或漢字        // \s    匹配任意的空白符        // \d    匹配數字        // \b    匹配單詞的開始或結束        //  ^    匹配字串的開始。如 @"^\\d{2}" : 表示以2數字開頭,“345dd”匹配1個,“1d2e33”沒有匹配        //  $    匹配字串的結束。如 @"\\d{2}$" :表示以2數字結尾,“ddd22”匹配1個,"dd3s3s"沒有匹配        //  例如手機:@"^1[3578]\\d{9}$" ,表示以1開頭,中間匹配任意3,5,7,8 ,最後以9個數字結尾        //  當然,正確的手機"1[3578]\\d{9}$"和"1[3578]\\d{9}" 寫都是可以匹配的。                //        *    重複零次或更多次        //        +    重複一次或更多次        //        ?    重複零次或一次                NSString *userName = @"13800138000";                NSString *pattern = @"^1[3578]\\d{9}$";        NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:pattern options:0 error:nil];                // 測試字串        NSArray *resultArray = [regex matchesInString:userName options:0 range:NSMakeRange(0, userName.length)];                NSLog(@"%zd",resultArray.count);    }    return 0;}

 

列印出匹配的字元

        NSString *userName = @"ddd333jda892dd34dsss";                NSString *pattern = @"[a-zA-Z]+"; // 匹配一次或更多次,會列印出連續的英文        NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:pattern options:0 error:nil];                NSArray *resultArray = [regex matchesInString:userName options:0 range:NSMakeRange(0, userName.length)];                for (NSTextCheckingResult *result in resultArray) {             NSLog(@"%@ %@",NSStringFromRange(result.range),[userName substringWithRange:result.range]);        }

結果(會列印出連續的結果):

 

iOS Regex

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.