iOS 和Android中的正则表达式简单使用
2014-02-07 17:30
375 查看
ios 中需要使用NSRegularExpression类,NSTextCheckingResult类。
下面给出最基本的实现代码
它的结果如下
这里每个rang的含义如下,matchRange表示找到的每个匹配串的总体位置,firstHalfRange则表示第一个表达式(a.*)的匹配范围,当然这个范围是总范围的一部分。关于为什么匹配到 "ab ab ab" 而不是 ab,这根据系统的处理方法而定,可能有方法进行设定,没有研究过。
如果仅仅想处理第一个匹配的结果,那么可以使用以下的代码,这种比较常用
Android中需要使用Pattern 和Matcher2个类,其实和ios的基本思路是一致的!
下面给出最基本的实现代码
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); }
相关文章推荐
- iOS 正则表达式的简单使用介绍
- iOS之正则表达式的简单使用
- ios 正则表达式简单使用。
- IOS成长之路-正则表达式的简单使用
- IOS成长之路-正则表达式的简单使用
- 正则表达式简单语法规则和IOS的使用
- 我的Android进阶之旅------>Android使用正则表达式匹配扫描指定目录下的所有媒体文件(音乐、图像、视频文件)
- awk-grep-sed简单使用总结(正则表达式的应用)
- Java中使用Socket完成简单的远程计算(含粗糙界面和正则表达式判断数字类型)
- 正则表达式在IOS中的应用及IOS中三种正则表达式的使用与比较
- 在Python中使用正则表达式同时匹配邮箱和电话并进行简单的分类
- iOS中正则表达式的使用方法及学习介绍
- iOS正则表达式的使用
- ios中NSPredicate的用法(正则表达式使用)
- iOS 常用的正则表达式和谓词的配合使用
- java爬取网页内容 简单例子(1)——使用正则表达式
- python正则表达式简单使用
- iOS开发中使用正则表达式
- IOS使用第三方工具(RegexKitLite)实现正则表达式
- iOS 中正则表达式的使用