NSRegularExpression搜索字符串" * string *"

时间:2015-03-20 09:37:20

标签: ios regex nsregularexpression

我有一个字符串列表我希望搜索字符串像 A 意味着它只出现在中间而不是第一个或最后一个。我的代码在这里: 当我运行所有3个案件都是真的,但只有案例“う上あ”是真的

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    NSArray *array = @[@"上あう", @"う上あ", @"あう上"];
    NSString *stringNeedToFind = @"*上*";
    for (NSString *string in array) {
        if ([[self regularExpressionFromValue: stringNeedToFind] numberOfMatchesInString:string options: 0 range: NSMakeRange(0, string.length)]) {
            NSLog(@"String containt.");
        }
    }
}

- (NSRegularExpression *) regularExpressionFromValue: (NSString *) value
{
    NSString *pattern = [NSRegularExpression escapedPatternForString: value];
    pattern = [pattern stringByReplacingOccurrencesOfString: @"\\*" withString: @".*"];
    pattern = [pattern stringByReplacingOccurrencesOfString: @"\\?" withString: @"."];
    pattern = [pattern stringByReplacingOccurrencesOfString: @".*.*.*" withString: @"\\*"];
    pattern = [pattern stringByReplacingOccurrencesOfString: @"..." withString: @"\\?\\?\\?"];
    pattern = [NSString stringWithFormat: @"^%@$", pattern];
    return [NSRegularExpression regularExpressionWithPattern: pattern options: 0 error: NULL];
}

1 个答案:

答案 0 :(得分:1)

据我所知,星号(*)用作运算符来检查字符(集)是否存在0次或更多次。我认为你应该使用加号(+),例如像这样:^。+上。+ $,意思是在开始和结束时应该有1个或更多的字符。