【问题标题】:How can I replace strings between a pattern for an NSString?如何在 NSString 的模式之间替换字符串?
【发布时间】:2019-08-06 02:49:44
【问题描述】:

考虑以下模式的 NSString:

(foo('Class 0')bar('Class 1')baz('Class 2')

我只需要返回foobarbaz。有什么办法至少可以使用正则表达式将'Class 0' 替换为某个单个字符?

我试过了:

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\(.*?\\)"
                                                                         options:NSRegularExpressionCaseInsensitive
                                                                           error:nil];
text = [regex stringByReplacingMatchesInString:text options:0 range:NSMakeRange(0, [text length]) withTemplate:@""];

【问题讨论】:

  • 您的问题是询问两种相互冲突的方法。你想返回三个字符串还是真的想用空格或其他东西替换('Class X') 部分?换句话说,你想要一个包含 3 个字符串的数组,还是想要一个包含 "foo bar baz" 的字符串?
  • 后者 - foo bar baz
  • 而在foo 之前的( 实际上是您要修改的字符串的一部分吗?

标签: objective-c regex nsstring


【解决方案1】:

如果我正确理解了您的情况,您需要从上面的字符串中解析出foobarbaz。下面的代码将执行此操作,并在数组中返回 foobarbaz

正如您将在代码中看到的,我们匹配一个单词和一个左括号,然后以编程方式修剪掉括号。可能有一个更好的正则表达式不需要修剪,但我无法使用 NSRegularExpression 来实现。

NSString *text = @"(foo('Class 0')bar('Class 1')baz('Class 2')";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[a-z]+[\(]"
                                          options:NSRegularExpressionCaseInsensitive
                                            error:nil];

NSMutableArray *output = [[NSMutableArray alloc] init];
[regex enumerateMatchesInString:text
                        options:0
                          range:NSMakeRange(0, [text length])
                     usingBlock:^(NSTextCheckingResult * _Nullable result, NSMatchingFlags flags, BOOL * _Nonnull stop) {

                         NSString *rawMatch = [text substringWithRange:result.range];
                         NSString *trimmed = [rawMatch substringToIndex:(rawMatch.length - 1)];
                         [output addObject:trimmed];
                     }];

要获取一个字符串,就像您在上面评论中提到的那样,只需使用

NSString *finalString = [output componentsJoinedByString:@" "];

【讨论】:

    【解决方案2】:

    我只会使用:

    NSString *string = @"foo('Class 0')bar('Class 1')baz('Class 2')";
    NSString *output = [string stringByReplacingOccurrencesOfString:@"\\('[^')]*'\\)"
                                                         withString:@" "
                                                            options:NSRegularExpressionSearch
                                                              range:NSMakeRange(0, string.length)];
    NSLog(@"%@", output); // foo bar baz
    

    用空格替换 ('') 之间的任何内容。模式[^')] 意味着我们不希望)'之间出现字母。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-06
      • 2023-02-04
      • 2016-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多