我不知道应该怎么做,我尝试过使用如下代码:
NSString *stringToFind = @"Hi";
NSString *fullString = @"Hi Objective C!";
NSRange range = [fullString rangeOfString :stringToFind];
if (range.location != NSNotFound)
{
NSLog(@"I found something.");
}
Run Code Online (Sandbox Code Playgroud)
但它不符合我的需要,我想搜索一个像#customstring(#表示标签)的字符串,其中标签由用户指定,所以他们输入这样的东西Something #hello #world,我想要做的是搜索所有的#和字符串附加到它并保存在某处.
编辑:创建的标记字符串,我将其保存在plist中,但是当我保存它时,它只保存一个标记,因为我只是将字符串指定为标记.像这样:
[db addNewItem:label tagString:tag];
Run Code Online (Sandbox Code Playgroud)
我需要创建所有标签.例如在我的日志中:
我记录了tag,这就出现了#tag,我tag再次使用这样的两个标签登录Something #hello #world我得到两个这样的标签:#hello&#world每个单独的日志.
我想要的结果是:
#hello, #world然后将其存储在一个字符串中并保存到我的DB.
你应该使用正则表达式:
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
Run Code Online (Sandbox Code Playgroud)
编辑要获取没有哈希字符的标记#,您应该在正则表达式中使用捕获组,如下所示:
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
Run Code Online (Sandbox Code Playgroud)
编辑要获取包含除标记之外的输入字符串的字符串,可以使用以下方法:
NSString *stringWithoutTags = [regex stringByReplacingMatchesInString:input options:0 range:NSMakeRange(0, input.length) withTemplate:@""];
NSLog(@"%@", stringWithoutTags);
// Something
Run Code Online (Sandbox Code Playgroud)
编辑现在你有了不同的标签,你可以创建一个包含它们的字符串,如下所示:
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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
994 次 |
| 最近记录: |