ios 使用NSRegularExpression解析正则表达式(TextKit中用到)
2015-04-27 11:26
423 查看
初始化一个 NSRegularExpression 对象 注:_str是要匹配的字符串
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"http://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?" options:NSRegularExpressionCaseInsensitive error:nil];
获得所有匹配了表达式的字符串。
NSArray *array = nil;
array = [regex matchesInString:_str options:0 range:NSMakeRange(0, [_str length])];
NSString *str1 = nil;
for (NSTextCheckingResult* b in array)
{
str1 是每个和表达式匹配好的字符串。
str1 = [_str substringWithRange:b.range];
NSLog(@" str 1 is %@",str1);
}
获得匹配的字符串的个数
NSUInteger numberOfMatches = [regex numberOfMatchesInString:_str options:0 range:NSMakeRange(0, [_str length])];
替换匹配的字符串 $0很重要 $0不行的话 $1依此类推 打印了看结果
NSString *modifiedString = [regex stringByReplacingMatchesInString:_str
options:0
range:NSMakeRange(0, [_str length])
withTemplate:@"<a href=\"$0\">$0</a>"];
NSLog(@"######## the modified string is %@",modifiedString);
转自:http://blog.csdn.net/paul_wuhaha/article/details/7406778
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"http://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?" options:NSRegularExpressionCaseInsensitive error:nil];
获得所有匹配了表达式的字符串。
NSArray *array = nil;
array = [regex matchesInString:_str options:0 range:NSMakeRange(0, [_str length])];
NSString *str1 = nil;
for (NSTextCheckingResult* b in array)
{
str1 是每个和表达式匹配好的字符串。
str1 = [_str substringWithRange:b.range];
NSLog(@" str 1 is %@",str1);
}
获得匹配的字符串的个数
NSUInteger numberOfMatches = [regex numberOfMatchesInString:_str options:0 range:NSMakeRange(0, [_str length])];
替换匹配的字符串 $0很重要 $0不行的话 $1依此类推 打印了看结果
NSString *modifiedString = [regex stringByReplacingMatchesInString:_str
options:0
range:NSMakeRange(0, [_str length])
withTemplate:@"<a href=\"$0\">$0</a>"];
NSLog(@"######## the modified string is %@",modifiedString);
转自:http://blog.csdn.net/paul_wuhaha/article/details/7406778
相关文章推荐
- IOS 关于使用RegexKitLite 的错误 (再之前 CommonUtility.h 需要用到)
- iOS 中TextKit的使用中,设置部分字体,出现的问题及解决方法
- iOS文本布局探讨之三——使用TextKit框架进行富文本布局
- iOS textFiled 在storyBoard中的使用
- XZ_iOS之使用textView实现占位文字
- iOS使用第三方工具(RegexKitLite)实现正则表达式
- 第一篇、Swift_Textkit的基本使用
- PlatinumKit-iOS Platinum的使用导入
- iOS 使用AFNetworking遇到异常 Request failed: unacceptable content-type: text/html
- iOS使用runtime修改文本框(TextField)的占位文字颜色
- iOS文本布局探讨之二——关于TextKit框架中的字体描述
- iOS云存储:CloudKit 基本使用教程 增删改查(Swift)
- iOS7.0使用语音输入时包含未解析完成的语音时,点击发送清空textview产生crash问题
- ios开发中经常用到xcode使用小技巧
- iOSJsonKit的使用
- 【iOS系列】-textView的非常规使用
- 详解iOS应用程序内使用IAP/StoreKit付费、沙盒(SandBox)测试、创建测试账号流程!
- iOS-TextKit
- ios MKNetworkKit 的使用
- 【iOS开发必收藏】详解iOS应用程序内使用IAP/StoreKit付费、沙盒(SandBox)测试、创建测试账号流程!【2012-12-11日更新获取"产品付费数量等于0的问题"】