本文介绍了在objective-C中解析以@和#开头的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图解析一个具有以下格式的字符串:

So I am trying to parse a string that has the following format:

或者,它也可以用空格分隔:

or, it can also be separated by spaces:

以下是我现在的表现:

- (void) parseTagsInComment:(NSString *) comment
{
    if ([comment length] > 0){
        NSArray * stringArray = [comment componentsSeparatedByString:@" "];
        for (NSString * word in stringArray){

        }
    }
}

我已经通过空间工作分离了组件,但如果它没有空间怎么办...如何迭代这些单词?我正在考虑使用正则表达式..但我不知道如何在Objective-C中编写这样的正则表达式。对于这两种情况的正则表达式有什么想法吗?

I've got the components separated by space working, but what if it has no space.. how do I iterate through these words? I was thinking of using regex.. but I have no idea on how to write such regex in objective-C. Any idea, for a regex that would cover both of these cases?

这是我的第一次尝试:

NSError * error;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(@|#)\\S+" options:NSRegularExpressionCaseInsensitive error:&error];

    NSArray* wordArray = [regex matchesInString:comment
                                      options:0 range:NSMakeRange(0, [comment length])];

    for (NSString * word in wordArray){

    }

哪个不起作用..我认为我的正则表达式是错误的。

Which doesn't work.. I think my regex is wrong.

推荐答案

这是一种方法它使用NSScanner将分隔的字符串和它们的范围的字符串表示形式放入一个数组中(这假设您的原始字符串以#开头 - 如果它没有并且您需要它,那么只需将哈希添加到字符串中在开始时。)

Here is a way to do it using NSScanner that puts the separated strings and a string representation of their ranges into an array (this assumes that your original string started with a # -- if it doesn't and you need it to, then just prepend the hash to the string at the start).

NSMutableArray *array = [NSMutableArray array];
    NSString *str = @"#baz@marroon#red#blue #big@cat#dog";
    NSScanner *scanner = [NSScanner scannerWithString:str];
    NSCharacterSet *searchSet = [NSCharacterSet characterSetWithCharactersInString:@"#@"];
    NSString *outputString;

    while (![scanner isAtEnd]) {
        [scanner scanUpToCharactersFromSet:searchSet intoString:nil];
        [scanner scanCharactersFromSet:searchSet intoString:&outputString];
        NSString *symbol = [outputString copy];
        [scanner scanUpToCharactersFromSet:searchSet intoString:&outputString];
        NSString *wholePiece = [[symbol stringByAppendingString:outputString]stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        NSString *rangeString = NSStringFromRange([str rangeOfString:wholePiece]);
        [array addObject:wholePiece];
        [array addObject:rangeString];
    }
    NSLog(@"%@",array);

这篇关于在objective-C中解析以@和#开头的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 03:39