OCRegex的使用,OCRegex使用

來源:互聯網
上載者:User

OCRegex的使用,OCRegex使用

OC中一般Regex的使用方法為2步

1.建立一個Regex對象

2.利用Regex來測試對應的字串

例如

    NSString *checkString = @"a34sd231";    //1.建立Regex,[0-9]:表示‘0’到‘9’的字元的集合    NSString *pattern = @"[0-9]";    //1.1將Regex設定為OC規則    NSRegularExpression *regular = [[NSRegularExpression alloc] initWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil];    //2.利用規則測試字串擷取匹配結果    NSArray *results = [regular matchesInString:checkString options:0 range:NSMakeRange(0, checkString.length)];    NSLog(@"%ld",results.count);

擷取列印結果,從checkString上分析為數位字元有5

所以可以得出一個結論,Regex的作用就是把多可字串雜糅到一個運算式中

到這裡就能大概明白Regex的意義了,接下來介紹一部分常用的Regex字元

/* []:找到內部的某一個字元 [a-zA-Z0-9]  ===> 代表字元或數字 \\d  ====>代表數字 {2}:代表有2個 {2,4}:代表有2到4個 // ? + * ^ $ . ?: 代表0或1個 +: 代表至少1個 *: 代表0個或多個 ^: 代表以...開頭 $: 代表以...結束 .: 代表除分行符號以外的任一字元 */
//代表一個數字字元
NSString *pattern = @"\\d";
//代表2到5個連續的數字
NSString *pattern = @"\\d{2,5}";
//qq帳號的Regex
NSString *pattern = @"^[1-9]\\d{4,10}";
//電話號碼格式的Regex
NSString *pattern = @"^((13[0-9])|(15[3-5])|(18[07-9]))\\d{8}$"
//郵箱的Regex
NSString *pattern =@"^.*@..+\\.[a-zA-Z]{2,4}$"

這樣根據需要的匹配規則來設定Regex就可以判斷字串是否為符合類型

若有一個長串字串就要對其中部分進行表情、url、@(呼叫)或#話題# 的匹配判斷

則需要多個Regex來進行判斷

//需要被篩選的字串NSString *str = @"#今日要聞#[偷笑] http://asd.fdfs.2ee/aas/1e @sdf[test] #你確定#@rain李23: @張三[挖鼻屎]m123m";    //表情Regex    //  \\u4e00-\\u9fa5 代表unicode字元    NSString *emopattern = @"\\[[a-zA-Z\\u4e00-\\u9fa5]+\\]";    //@Regex    NSString *atpattern = @"@[0-9a-zA-Z\\u4e00-\\u9fa5]+";    //#...#Regex    NSString *toppattern = @"#[0-9a-zA-Z\\u4e00-\\u9fa5]+#";    //urlRegex    NSString *urlpattern = @"\\b(([\\w-]+://?|www[.])[^\\s()<>]+(?:\\([\\w\\d]+\\)|([^[:punct:]\\s]|/)))";    //設定總的Regex    NSString *pattern = [NSString stringWithFormat:@"%@|%@|%@|%@",emopattern,atpattern,toppattern,urlpattern];    //根據Regex設定OC規則    NSRegularExpression *regular = [[NSRegularExpression alloc] initWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil];    //擷取匹配結果    NSArray *results = [regular matchesInString:str options:0 range:NSMakeRange(0, str.length)];    //NSLog(@"%@",results);    //遍曆結果    for (NSTextCheckingResult *result in results) {        NSLog(@"%@ %@",NSStringFromRange(result.range),[str substringWithRange:result.range]);    }

獲得結果

有了上面的示範就可以大致寫出系統方法使用的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.