Pergunta

I've got a bit of code (below) which parses a uitextfield for hashtags and @-symbols whenever the text changes. It works fine with:

#one #two

..but fails when the two has tags are next to each other, like this:

#one#two

This is my code:

- (IBAction)changed:(UITextField*)sender
{
    NSRegularExpression *regexp = [[NSRegularExpression alloc] initWithPattern:@"(?:^|\\s|[\\p{Punct}&&[^/]])((#[\\p{L}0-9-_]+)|(@[\\p{L}0-9-_\\.]+))" options:NSRegularExpressionCaseInsensitive error:nil];
    NSArray *matches = [regexp matchesInString: [sender text] options:0 range:NSMakeRange(0, [[sender text]  length])];
    NSMutableString *output = [[NSMutableString alloc] init];
    for (NSTextCheckingResult *linkRange in matches) {
        NSString *match = [[sender text] substringWithRange:[linkRange rangeAtIndex:1]];
        [output appendString:match];
        [output appendString:@"\n"];
    }
    self.label.text = output;
}

What is the correct regex to deal with both space and no space?

Foi útil?

Solução

I didn't analyze your whole pattern but I tested your code and to detect only hashtags you should use:

NSRegularExpression *regexp = [[NSRegularExpression alloc] initWithPattern:@"#[^# ]+" options:NSRegularExpressionCaseInsensitive error:nil];

Output:

output __NSCFString * @"#dl\n#laklkjdfg\n#glkjs\n" 0x1839cab0

for:

NSString *text = @"#dl#laklkjdfg #glkjs";
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top