NSRegularExpression 删除行尾括号内的数字

NSRegularExpression to remove digits within parentheses at the end of a line

我觉得我已经用尽了我能想到的每一个正则表达式并阅读了我能得到的每一篇 NSRegularExpression 文档,但我仍然无法弄清楚这一点。

我有一些以括号内的数字结尾的 NSString(类似于 "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

感谢任何帮助!

你应该使用

\s*\(\d+\)$

demo

在 Objective-C 中,贴标为 @"\s*\(\d+\)$"

您的正则表达式 - [\s\(\d+\)$] - 将所有子模式括在方括号中,从而创建一个匹配 1 个字符的字符 class:空格,或 (,或数字,或 +,或),或$

所以,你需要去掉方括号,并在空白处添加一个*量词 shorthand class \s 以匹配所有前导空白.