您的位置:首页 > 移动开发 > Android开发

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

2014-02-07 17:30 375 查看
ios 中需要使用NSRegularExpression类,NSTextCheckingResult类。

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

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;
}];


它的结果如下



这里每个rang的含义如下,matchRange表示找到的每个匹配串的总体位置,firstHalfRange则表示第一个表达式(a.*)的匹配范围,当然这个范围是总范围的一部分。关于为什么匹配到 "ab ab ab" 而不是 ab,这根据系统的处理方法而定,可能有方法进行设定,没有研究过。

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

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];
} }


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

String patternStr = "[0-9:]*";

Pattern p = Pattern.compile(patternStr);

Matcher m = p.matcher(originalStr);

if (m.find()) {
returnStr = m.group(0);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: