【发布时间】:2015-10-05 14:55:09
【问题描述】:
我觉得我已经用尽了我能想到的每一个正则表达式,并阅读了我能拿到的每一个 NSRegularExpression 文档,但我仍然无法弄清楚这一点。
我有一些 NSStrings 以括号内的数字结尾(例如“blah blah blah (33)”。我想删除括号、空格和数字,但前提是它在行尾匹配并且仅当括号的内容仅为数字时(前面的示例为“blah blah blah”)。我下面的正则表达式很接近,但如果正则表达式中有非数字字符,它将匹配,如果有,它将匹配更多内容在字符串末尾,括号后:
NSArray *testStrings = @[@"hello (2)", @"hello (22)", @"hello (22) a", @"hello (2s)"];
for (NSString *msg in testStrings) {
NSError *error = NULL;
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern: @"[\\s\(\\d+\\)$]"
options: NSRegularExpressionCaseInsensitive
error: &error];
if (!error) {
NSLog(@"%lu", [regex numberOfMatchesInString:msg options:0 range:NSMakeRange(0, [msg length])]);
NSString* plainText = [regex stringByReplacingMatchesInString: msg
options: 0
range: NSMakeRange(0, [msg length])
withTemplate: @""];
NSLog(@"%@", plainText);
}
}
下面是输出:
test[93719:10248184] 4
test[93719:10248184] hello
test[93719:10248184] 5
test[93719:10248184] hello
test[93719:10248184] 6
test[93719:10248184] helloa
test[93719:10248184] 4
test[93719:10248184] hellos
感谢任何帮助!
【问题讨论】:
-
stribizhevs 的答案是正确的,虽然你想匹配像
hello (1) world (23)这样的字符串吗?
标签: regex nsstring nsregularexpression