在Objective-C中对Toknize NSString进行两次Tokenize

Mig*_*l E 1 objective-c tokenize

我对objective-c没有太多经验,对不起,如果这很明显的话.

我需要的是将NSString分成标记.令牌由空格或另一个符号(不是字母)分隔.问题是我想保留分隔符,除非它们是空格.

例句:"abc,d's,e f." 从这里我想得到:

"a"
"b"
"c"
","
"d"
"'"
"s"
","
"e"
"f"
"."
Run Code Online (Sandbox Code Playgroud)

使用此代码:

NSMutableCharacterSet *separators = [NSMutableCharacterSet punctuationCharacterSet];
[separators formUnionWithCharacterSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

NSArray *parse_array = [intext componentsSeparatedByCharactersInSet:separators];
Run Code Online (Sandbox Code Playgroud)

我只收到了这些信件.如果我只是过滤空白和NL我会将这些符号和字母一起使用.我需要的是按顺序执行两个解析(首先是空格和Nl,然后是标点符号),但我真的不知道如何在objective-c中执行它.任何人都可以给我一个提示吗?

谢谢!

Tod*_*orf 5

查看我的开源Cocoa String标记化/解析工具包:ParseKit:

http://parsekit.com

ParseKit包含一个非常强大/灵活的tokenizer类:PKTokenizer.默认情况下,PKTokenizer将静默使用空格标记而不报告它们.(在这种情况下,这就是您想要的,但如果您不这样做,则可以配置该行为.)

以下是您可以PKTokenizer用于此特定任务的方式:

// create the tokenizer with your string
NSString *inStr = @"a b c,d's, e f.";
PKTokenizer *t = [PKTokenizer tokenizerWithString:inStr];

// configure the tokenizer to not allow apostrophes inside words (that's the default)
[t.wordState setWordChars:NO from:'\'' to:'\''];

// loop thru the input and concat the non-whitespace chars
PKToken *eof = [PKToken EOFToken];
PKToken *tok = nil;

NSMutableArray *outStrs = [NSMutableArray array];
while ((tok = [t nextToken]) != eof) {
    [outStrs addObject:tok.stringValue];
}
Run Code Online (Sandbox Code Playgroud)

outStrs 包含:

    "a""b""c"",""d""'""s"",""e""f""."

对于这个特定的任务,ParseKit可能有点过分.但是如果你有几个类似的任务,它可能值得一试,因为它可以节省你的时间/痛苦.