0

これをどのように行うべきかわかりません。次のようなコードを使用してみました。

NSString *stringToFind = @"Hi";
NSString *fullString = @"Hi Objective C!";
NSRange range = [fullString rangeOfString :stringToFind];
if (range.location != NSNotFound)
{
    NSLog(@"I found something.");
}

しかし、それは私のニーズに合っていません#customstring。ユーザーがタグを指定する (# はタグを意味します) のような文字列を検索したいので、このようなものを入力しSomething #hello #worldます#。文字列を添付して、どこかに保存します。

編集:作成されたタグ文字列は、plist に保存していますが、保存すると、文字列をタグとして指定しただけなので、1 つのタグしか保存されません。このように:

[db addNewItem:label tagString:tag];

作成したすべてのタグが必要です。たとえば、私のログでは:

私はログに記録tagし、これが発生し#tag、次tagのような 2 つのタグで再度ログに記録します。Something #hello #world次のような 2 つのタグを取得します: #hello&#worldそれぞれ個別のログ。

私が望む結果はこれです:

#hello, #worldそれを文字列に保存して my に保存しますDB

4

2 に答える 2

6

正規表現を使用する必要があります。

NSString *input = @"Something #hello #world";

NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:@"#\\w+" options:0 error:nil];
NSArray *matches = [regex matchesInString:input options:0 range:NSMakeRange(0, input.length)];

NSLog(@"%d matches found.", matches.count);
for (NSTextCheckingResult *match in matches) {
    NSString *tag = [input substringWithRange:[match range]];
    NSLog(@"%@", tag);
}
// #hello
// #world

編集ハッシュ文字なしでタグを取得するには#、次のように正規表現でキャプチャ グループを使用する必要があります。

NSString *input = @"Something #hello #world";

NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:@"#(\\w+)" options:0 error:nil];
NSArray *matches = [regex matchesInString:input options:0 range:NSMakeRange(0, input.length)];

NSLog(@"%d matches found.", matches.count);
for (NSTextCheckingResult *match in matches) {
    NSString *tag = [input substringWithRange:[match rangeAtIndex:1]];
    NSLog(@"%@", tag);
}
// hello
// world

EDITタグを除く入力文字列を含む文字列を取得するには、次のメソッドを使用できます。

NSString *stringWithoutTags = [regex stringByReplacingMatchesInString:input options:0 range:NSMakeRange(0, input.length) withTemplate:@""];
NSLog(@"%@", stringWithoutTags);
// Something

編集さまざまなタグが用意されたので、次のようにそれらを含む文字列を作成できます。

NSMutableArray *tagsArray = [NSMutableArray array];
for (NSTextCheckingResult *match in matches) {
    NSString *tag = [input substringWithRange:[match range]];
    [tagsArray addObject:tag];
}
NSString *tagsString = [tagsArray componentsJoinedByString:@", "];
NSLog(@"tagsString: %@", tagsString);
于 2012-04-22T18:10:29.140 に答える
-1

私はそれを#で区切られた配列に分割し、次にそれぞれをスペースで分割し、それぞれの最初の単語を選択します。

  NSArray *chunks = [string componentsSeparatedByString: @"#"];
于 2012-04-22T18:07:33.583 に答える