将NSString分隔为NSArray,但允许使用引号将单词分组 [英] Separating NSString into NSArray, but allowing quotes to group words

查看:87
本文介绍了将NSString分隔为NSArray,但允许使用引号将单词分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个搜索字符串,人们可以在其中使用引号将短语分组在一起,然后将其与各个关键字混合使用。例如,这样的字符串:

I have a search string, where people can use quotes to group phrases together, and mix this with individual keywords. For example, a string like this:

"Something amazing" rooster

我想将其分离到一个NSArray中,以使它具有令人惊讶的东西(不带引号) )作为一个元素,而 rooster 作为另一个元素。

I'd like to separate that into an NSArray, so that it would have Something amazing (without quotes) as one element, and rooster as the other.

componentsSeparatedByString componentsSeparatedByCharactersInSet 似乎也符合要求。有简单的方法吗?还是我应该自己编写代码?

Neither componentsSeparatedByString nor componentsSeparatedByCharactersInSet seem to fit the bill. Is there an easy way to do this, or should I just code it up myself?

推荐答案

我最终还是选择了常规方法表达式,就像我已经使用RegexKitLite一样,并创建此NSString + SearchExtensions类别。

I ended up going with a regular expression as I was already using RegexKitLite, and creating this NSString+SearchExtensions category.

.h:

//  NSString+SearchExtensions.h
#import <Foundation/Foundation.h>
@interface NSString (SearchExtensions)
-(NSArray *)searchParts;
@end

.m:

//  NSString+SearchExtensions.m
#import "NSString+SearchExtensions.h"
#import "RegexKitLite.h"

@implementation NSString (SearchExtensions)

-(NSArray *)searchParts {
    __block NSMutableArray *items = [[NSMutableArray alloc] initWithCapacity:5];

    [self enumerateStringsMatchedByRegex:@"\\w+|\"[\\w\\s]*\"" usingBlock: ^(NSInteger captureCount,
       NSString * const capturedStrings[captureCount],
       const NSRange capturedRanges[captureCount],
       volatile BOOL * const stop) {

        NSString *result = [capturedStrings[0] stringByReplacingOccurrencesOfRegex:@"\"" withString:@""];

        NSLog(@"Match: '%@'", result);
        [items addObject:result];
    }];        
    return [items autorelease];
}
@end

这将返回包含搜索字符串的NSArray字符串,并删除短语周围的双引号。

This returns an NSArray of strings with the search strings, removing the double quotes that surround the phrases.

这篇关于将NSString分隔为NSArray,但允许使用引号将单词分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆