我对正则表达式很陌生,正在努力学习。
这是我的字符串:
Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)
我想把它拆分成一个数组,如下所示:
@[@"Mozzila", @"4.0", @"compatible", @"MSIE 5.0", @"Windows NT", @"DigExt"];
这是我试过的代码:
NSString *expression = @"Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)";
NSRegularExpression *testExpression = [NSRegularExpression regularExpressionWithPattern: @"([a-zA-Z]+)/([1-9.]+) \(([a-z]+); ([a-zA-Z .]+); ([a-zA-Z ]+); ([a-zA-Z]+)\)" options:NSRegularExpressionCaseInsensitive error:nil];
options:NSRegularExpressionCaseInsensitive error:nil];
NSArray *matches = [testExpression matchesInString:expression
options:0
range:NSMakeRange(0, [expression length])];
NSLog(@"%@",matches);
也试过:
[testExpression enumerateMatchesInString:expression
options:0
range:NSMakeRange(0, [expression length])
usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
NSLog(@"Value: %@", [expression substringWithRange:[result rangeAtIndex:1]]);
}];
还有:
NSRegularExpression *testExpression = [NSRegularExpression
regularExpressionWithPattern: @"(\w+)/(\w+) \((\w+);([\w .]+); ([\w ]+); (\w+)\)" options:NSRegularExpressionCaseInsensitive
error:nil];
但是日志是空的。我做错了什么?
最佳答案
NSString *expression = @"Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)";
NSRegularExpression *testExpression = [NSRegularExpression regularExpressionWithPattern:@"(.+)/([0-9\\.]+) \\(([^)]*).*"
options:NSRegularExpressionCaseInsensitive error:nil];
NSArray *matches = [testExpression matchesInString:expression
options:0
range:NSMakeRange(0, [expression length])];
NSLog(@"%@",matches);
NSMutableArray *array = [@[] mutableCopy];
[matches enumerateObjectsUsingBlock:^(NSTextCheckingResult *obj, NSUInteger idx, BOOL *stop) {
for (int i = 1; i< [obj numberOfRanges]; ++i) {
NSRange range = [obj rangeAtIndex:i];
NSString *string = [expression substringWithRange:range];
if ([string rangeOfString:@";"].location == NSNotFound) {
[array addObject: string];
} else {
NSArray *a = [string componentsSeparatedByString:@";"];
for (NSString *s in a) {
[array addObject: [s stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]];
}
}
}
}];
数组
包含
<__NSArrayM 0x10010d540>(
Mozilla,
4.0,
compatible,
MSIE 5.0,
Windows NT,
DigExt
)
@"(.+)/([0-9\\.]+) \\(([^)]*).*"
^__^ capture group 1
^_________^ capture group 2
^ the char (
^_____^ capture group 3
- 捕获组 1 捕获所有可打印的字符,直到/。
- 捕获组 2 捕获所有数字和点。我们必须用
\\
转义点,否则它会再次代表任何字符。 \\(
表示(
将跟在后面,但由于我们没有将它包含在我们的捕获组中,所以我们不太关心它。- 捕获第 3 组
([^)]*)
说“任何可打印但不是)
现在我们遍历捕获组及其范围。我们从索引 1 开始,因为索引 0 将给出完整表达式的范围
([1-9.]+)
这将不匹配 0
并且点代表任何可打印字符。你要
([0-9\\.]+)
关于objective-c - 使用正则表达式拆分字符串 - objective-C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19356692/