提供一个网页版的JavaScript 调试工具,非常给力:http://www.renrousousuo.com/tools/regex_debug.html
1: 如果在检索的文本中需要检索包含正则表达式的关键字,如 "[ ]" 那么在 拼装字符串时 需要加两个反斜杠(\\[)进行转义识别,否则会误判的
2: 在iOS中的正则表达式字符串 不需要左右侧加 /
1:NSRegularExpression 案例一. 在HTML字符串中 找寻出完整的 <img> 标签. 包含 /> 和 </img> 结尾两种情况
NSError *error;
NSString *strRegex = @"<img([^<]+)(/>|</img>)";
NSRegularExpression *reg = [NSRegularExpression regularExpressionWithPattern:strRegex options:NSRegularExpressionCaseInsensitive|NSRegularExpressionDotMatchesLineSeparators error:&error];
//无视大小写.
NSArray *matches = [reg matchesInString:@"所要查找的字符串" options:NSMatchingCompleted range:NSMakeRange(0, [muStrHTMLContent length])];
for (NSTextCheckingResult *match in matches) {
i++;
NSRange range = [match range];
NSLog(@"%d,%d,%@",range.location,range.length,[muStrCloneHTMLContent substringWithRange:range]);
}
2:NSRegularExpression 案例二. 对给定的字符串进行正则批量替换
NSError* error = NULL;
//(encoding=\")[^\"]+(\")
//分成三段来理解
/*
第一段:以某段字符做为起始 (encoding=\") 括号内为实际内容
第二段:对于包含中的定义,参见正则.
第三段:再以某段字符做为收尾 (\")
*/
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:@"(encoding=\")[^\"]+(\")"
options:0
error:&error];
NSString* sample = @"<xml encoding=\"abc\"></xml><xml encoding=\"def\"></xml><xml encoding=\"ttt\"></xml>";
NSLog(@"Start:%@",sample);
//对给定的字符串进行正则批量替换. $1 表示 是否保留起始 $2 表示 是否保留收尾
NSString* result = [regex stringByReplacingMatchesInString:sample
options:0
range:NSMakeRange(0, sample.length)
withTemplate:@"$1余书懿$2"];
NSLog(@"Result:%@", result);
3:案例三: 补全 json 字符串中 没有 双引号的 key
NSError* error = nil;
//(\\w+)(\\s*:\\s*)
NSRegularExpression* regex = [NSRegularExpression
regularExpressionWithPattern:@"(\\w+)(\\s*:\\s*)" options:0 error:&error];
NSString* sample = @"{[{a:b,av:a},{a:a,s:a}]}";
NSLog(@"Start:%@",sample);
//对给定的字符串进行正则批量替换. $1 $2 表示检索到的部位 打印看结果
NSString* result = [regex stringByReplacingMatchesInString:sample
options:0
range:NSMakeRange(0, sample.length)
withTemplate:@"\"$1\"$2"];
NSLog(@"Result:%@", result);