如何在NSString的模式之间替换字符串?

问题描述 投票:0回答:2

考虑以下模式的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:@""];
objective-c regex nsstring
2个回答
0
投票

如果我理解你的情况,你需要从上面的字符串中解析foobarbaz。下面的代码就是这样做的,并在数组中返回foobarbaz

正如您将在代码中看到的那样,我们匹配一个单词和一个开头的paren,然后以编程方式修剪parens。可能有一个更好的正则表达式,不需要修剪,但我无法使用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:@" "];

0
投票

我会用:

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

用空格替换('')之间的任何东西。模式[^')]意味着我们不希望)'letters出现在它们之间。

© www.soinside.com 2019 - 2024. All rights reserved.