IOS中Regex的使用

來源:互聯網
上載者:User

標籤:

Regex在IOS開發中的應用

Regex在字串尋找,替換,檢測中的應用非常廣泛,Regex是什麼,有怎樣的文法,我的另一篇部落格中有詳細的介紹:http://my.oschina.net/u/2340880/blog/403508。這裡只簡單說一下其概念 ,Regex是一種文法小巧簡單的語言,用來約束一些過濾字串條的條件。很多開發工具都有支援Regex的內容,IOS也不例外,在IOS中NSRegularExpression類就是一個專門來處理Regex的類。

一、初始化方法

初始化NSRegularExpression的方法有兩種,一個init方法和一個類方法。其作用基本是一樣的

+ (NSRegularExpression *)regularExpressionWithPattern:(NSString *)pattern options:(NSRegularExpressionOptions)options error:(NSError **)error;

- (instancetype)initWithPattern:(NSString *)pattern options:(NSRegularExpressionOptions)options error:(NSError **)error 


其中,pattern是Regex,options是參數。對於option參數,它是一個枚舉,表示正則模式的設定,如下:

typedef NS_OPTIONS(NSUInteger, NSRegularExpressionOptions) {   NSRegularExpressionCaseInsensitive             = 1 << 0, //不區分字母大小寫模式   NSRegularExpressionAllowCommentsAndWhitespace  = 1 << 1, //忽略掉Regex中的空格和#號之後的字元   NSRegularExpressionIgnoreMetacharacters        = 1 << 2, //將Regex整體作為字串處理   NSRegularExpressionDotMatchesLineSeparators    = 1 << 3, //允許.匹配任何字元,包括分行符號     NSRegularExpressionAnchorsMatchLines           = 1 << 4, //允許^和$符號匹配行的開頭和結尾   NSRegularExpressionUseUnixLineSeparators       = 1 << 5, //設定\n為唯一的行分隔字元,否則所有的都有效。   NSRegularExpressionUseUnicodeWordBoundaries    = 1 << 6 //使用Unicode TR#29標準作為詞的邊界,否則所有傳統Regex的詞邊界都有效};

注意:1、NSRegularExpressionCaseInsensitive模式下Regex aBc 會匹配到abc.

            2、NSRegularExpressionIgnoreMetacharacters模式下Regexa b c 會匹配到abc,Regexab#c會匹配到ab。

            3、NSRegularExpressionAllowCommentsAndWhitespace模式下Regex[a-z],會匹配到[a-z]。

二、擷取查詢結果

初始化完畢Regex的處理類後,我們需要進行Regex的查詢,IOS官方提供了兩種模式:

1、帶block模式的方法:

- (void)enumerateMatchesInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range usingBlock:(void (^)(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop))block;

使用舉例:

NSRegularExpression * regex = [[NSRegularExpression alloc]initWithPattern:@"[a-z]" options:NSRegularExpressionCaseInsensitive error:nil];    [regex enumerateMatchesInString:@"124a" options:NSMatchingReportProgress range:NSMakeRange(0, 4) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {        NSLog(@"%@",result);    } ];

注意:1、這個函數的一個參數options是一個枚舉,設定回調的方式,如下:

typedef NS_OPTIONS(NSUInteger, NSMatchingOptions) {   NSMatchingReportProgress         = 1 << 0, //找到最長的匹配字串後調用block回調   NSMatchingReportCompletion       = 1 << 1, //找到任何一個匹配串後都回調一次block   NSMatchingAnchored               = 1 << 2, //從匹配範圍的開始出進行極限匹配   NSMatchingWithTransparentBounds  = 1 << 3, //允許匹配的範圍超出設定的範圍   NSMatchingWithoutAnchoringBounds = 1 << 4  //禁止^和$自動匹配行還是和結束};

            2、block回調中的flags枚舉對應如下:

typedef NS_OPTIONS(NSUInteger, NSMatchingFlags) {   NSMatchingProgress               = 1 << 0, //匹配到最長串是被設定        NSMatchingCompleted              = 1 << 1, //全部分配完成後被設定       NSMatchingHitEnd                 = 1 << 2, //匹配到設定範圍的末尾時被設定      NSMatchingRequiredEnd            = 1 << 3, //當前匹配到的字串在匹配範圍的末尾時被設定        NSMatchingInternalError          = 1 << 4  //由於錯誤導致的匹配失敗時被設定   };

            3、還有一點需要注意,就是那個bool值stop,我們可以在block塊中設定它為YES,之後便會停止尋找。

2、非block的方法

這個方法會返回一個結果數組,將所有匹配的結果返回

- (NSArray *)matchesInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range;


這個方法會返回匹配到得字串的個數

- (NSUInteger)numberOfMatchesInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range;


這個方法會返回第一個查詢到得結果,這個NSTextCheckingResult對象中有一個range屬性,可以得到匹配到的字串的範圍。

- (NSTextCheckingResult *)firstMatchInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range;


這個方法直接返回匹配到得範圍,NSRange。

- (NSRange)rangeOfFirstMatchInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range;


三、一個輔助方法

在NSRegularExpression類中還提供了一個輔助方法:

+ (NSString *)escapedPatternForString:(NSString *)string;

它可以協助我們將Regex加上"\"進行保護,將元字元轉化成字面值。


到此,在IOS中Regex的基本用法就介紹完了,希望Regex的應用,能為你的項目節省更多時間。


疏漏之處 歡迎指正

學習使用 歡迎轉載







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.