首页 > 移动平台 > 详细

iOS 和Android中的正则表达式简单使用

时间:2014-02-07 21:17:51      阅读:680      评论:0      收藏:0      [点我收藏+]

ios 中需要使用NSRegularExpression类,NSTextCheckingResult类。

下面给出最基本的实现代码

bubuko.com,布布扣
 NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(a.*)(b)" options:NSRegularExpressionCaseInsensitive error:nil];
    
    
    __block NSUInteger count = 0;
    NSString *string = @" ab  ab   ab ";
    [regex enumerateMatchesInString:string options:0 range:NSMakeRange(0, [string                                                                           length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){
        NSLog(@"---------------------------find one match!");
        
        NSRange matchRange = [match range];
        NSRange firstHalfRange = [match rangeAtIndex:1];
        NSRange secondHalfRange = [match rangeAtIndex:2];
        
        NSLog(@"the string is %@",[string substringWithRange:matchRange]);
        NSLog(@"firstHalfRange is %@",[string substringWithRange:firstHalfRange]);
        NSLog(@"secondHalfRange is %@",[string substringWithRange:secondHalfRange]);
        
        
        
        if (++count >= 100) *stop = YES;
    }];
bubuko.com,布布扣

它的结果如下

bubuko.com,布布扣

这里每个rang的含义如下,matchRange表示找到的每个匹配串的总体位置,firstHalfRange则表示第一个表达式(a.*)的匹配范围,当然这个范围是总范围的一部分。

如果仅仅想处理第一个匹配的结果,那么可以使用以下的代码

bubuko.com,布布扣
NSTextCheckingResult *match = [regex firstMatchInString:string
                                                options:0
                                                  range:NSMakeRange(0, [string
length])];
if (match) {
    NSRange matchRange = [match range];
    NSRange firstHalfRange = [match rangeAtIndex:1];
    NSRange secondHalfRange = [match rangeAtIndex:2];
} }
bubuko.com,布布扣

 

Android中需要使用Pattern 和Matcher2个类,其实和ios的基本思路是一致的!

bubuko.com,布布扣
 String patternStr = "[0-9:]*";

 Pattern p = Pattern.compile(patternStr);

 Matcher m = p.matcher(originalStr);

 if (m.find()) {
         returnStr = m.group(0);
 }
bubuko.com,布布扣

iOS 和Android中的正则表达式简单使用

原文:http://www.cnblogs.com/breezemist/p/3539729.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!