前瞻 ( ?=
) 在这里是错误的,您没有正确地转义\d
(它变成\\d
),最后但并非最不重要的是,您遗漏了量词*
(0 次或多次) 和+
(1 次或多次):
NSString *aTestString = @"value=!@#777!@#value=@#$**888***";
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:@"value=[^\\d]*(\\d+)"
options:0
error:NULL
];
[regex
enumerateMatchesInString:aTestString
options:0
range:NSMakeRange(0, [aTestString length])
usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
NSLog(@"Value: %@", [aTestString substringWithRange:[result rangeAtIndex:1]]);
}
];
编辑:这是一个更精致的模式。它在 之前捕获一个单词=
,然后丢弃非数字并在之后捕获数字。
NSString *aTestString = @"foo=!@#777!@#bar=@#$**888***";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(\\w+)=[^\\d]*(\\d+)" options:0 error:NULL];
[regex
enumerateMatchesInString:aTestString
options:0
range:NSMakeRange(0, [aTestString length])
usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
NSLog(
@"Found: %@=%@",
[aTestString substringWithRange:[result rangeAtIndex:1]],
[aTestString substringWithRange:[result rangeAtIndex:2]]
);
}
];
// Output:
// Found: foo=777
// Found: bar=888