Estou tentando capturar um link do YouTube a partir de uma sequência de texto usando o NSRegularExpression, embora não tenha certeza de como capturar o link inteiro.
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:@"http://youtube.*"
options:NSRegularExpressionCaseInsensitive
error:&error];
Exemplo de string:
"Hello please take a look at the following: https://www.youtube.com/watch?v=C-UwOWB9Io4&feature=youtu.be For tomorrow thanks."
Alguma idéia de como isso pode ser alcançado?
Respostas:
3 para resposta № 1Isso pressupõe que o URL começa com "http" ou "https" e que não há espaços no URL e um espaço imediatamente após o URL, isso parece razoável.
NSString *searchString = @"Hello please take a look at the following: https://www.youtube.com/watch?v=C-UwOWB9Io4&feature=youtu.be For tomorrow thanks.";
NSRange searchRange = NSMakeRange(0, [searchString length]);
NSString *pattern = @"(http[s]?://www.youtube.com\S+)";
NSError *error = nil;
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
NSTextCheckingResult *match = [regex firstMatchInString:searchString options:0 range: searchRange];
NSRange matchRange = [match rangeAtIndex:1];
NSLog(@"matchRange: %@", NSStringFromRange(matchRange));
NSString *matchString = [searchString substringWithRange:matchRange];
NSLog(@"matchString: %@", matchString);
Saída:
matchRange: {43, 60}
matchString: https://www.youtube.com/watch?v=C-UwOWB9Io4&feature=youtu.be
Se você quiser o "www". para ser opcional, você pode usar o padrão i (ponta do chapéu para @MikeAtNobel para a idéia:
"(http[s]?://(?:www\.)?youtube.com\S+)"
Guia do Usuário da UTI: Expressões regulares