JavaScript正则匹配示例

匹配文章id使用原生跳转

1
2
3
4
var str = "http://bbs.pcauto.com.cn/topic-15113553.html";
var substr = str.match(/pcauto.com.cn\/topic-(\d*).html/);
console.log(substr);
console.log('匹配id='+substr[1]);

OC实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"pcauto.com.cn/topic-(\\d*).html" options:NSRegularExpressionCaseInsensitive error:nil];

//匹配第一个
NSTextCheckingResult *result = [regex firstMatchInString:searchText options:0 range:NSMakeRange(0, [searchText length])];
NSRange matchRange = [result rangeAtIndex:1];
NSString *matchString = [searchText substringWithRange:matchRange];
NSLog(@"searchText=%@",matchString);

//匹配所有
NSArray* matches = [regex matchesInString:searchText options:0 range:NSMakeRange(0, [searchText length])];
if (matches.count != 0)
{
NSLog(@"matches=%@",matches);
for (NSTextCheckingResult *match in matches) {
NSLog(@"match=%@", NSStringFromRange([match rangeAtIndex:2]));
NSRange matchRange = [match rangeAtIndex:1];
NSString *matchString = [searchText substringWithRange:matchRange];
NSLog(@"matchString=%@", matchString);
}
}
文章作者: kyren
文章链接: http://huluo666.github.io/2018/03/05/JavaScript正则匹配示例/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Kyren's Blog