2011-05-05 10 views
9

Actualmente estoy usando una UIWebView para estilizar las publicaciones de Twitter. Algunos tweets, por supuesto, contienen URL, pero no contienen las etiquetas <a>. Puedo extraer la URL, sin embargo, no estoy seguro de cómo agregar las etiquetas <a> y volver a colocarlas en el tweet. A continuación, utilizaré el mismo enfoque aquí para agregar enlaces a los @usernames y #hashtags. He aquí un ejemplo de mi código actual:NSRegularExpression: Reemplazar el texto de la url con <a> etiquetas

NSString *tweet = @"Sync your files to your Google Docs with a folder on your desktop. Like Dropbox. Good choice, Google storage is cheap. http://ow.ly/4OaOo"; 

NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:@"(?i)\\b((?:[a-z][\\w-]+:(?:/{1,3}|[a-z0-9%])|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:'\".,<>?«»“”‘’]))" options:NSRegularExpressionCaseInsensitive error:NULL]; 

NSString *match = [tweet substringWithRange:[expression rangeOfFirstMatchInString:tweet options:NSMatchingCompleted range:NSMakeRange(0, [tweet length])]]; 
NSLog(@"%@", match);// == http://ow.ly/4OaOo 

En última instancia, me gustaría que la cadena final a tener este aspecto:

Sync your files to your Google Docs with a folder on your desktop. Like Dropbox. Good choice, Google storage is cheap. <a href="http://ow.ly/4OaOo>http://ow.ly/4OaOo</a>

Cualquier ayuda sería muy apreciada.

Respuesta

15

Y aquí es una versión Objective-C:

NSString *regexToReplaceRawLinks = @"(\\b(https?):\\/\\/[-A-Z0-9+&@#\\/%?=~_|!:,.;]*[-A-Z0-9+&@#\\/%=~_|])"; 

NSError *error = NULL; 
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexToReplaceRawLinks 
                     options:NSRegularExpressionCaseInsensitive 
                     error:&error]; 

NSString *string = @"Sync your files to your Google Docs with a folder on your desktop. Like Dropbox. Good choice, Google storage is cheap. http://ow.ly/4OaOo"; 

NSString *modifiedString = [regex stringByReplacingMatchesInString:string 
                  options:0 
                  range:NSMakeRange(0, [string length]) 
                 withTemplate:@"<a href=\"$1\">$1</a>"]; 

NSLog(@"%@", modifiedString); 

he hecho algo como esto antes, pero utiliza javascript para hacerlo. Cuando la vista se ha cargado, utilice el método delegado webViewDidFinishLoad y ejecución de JavaScript:

- (void)webViewDidFinishLoad:(UIWebView *)webView 
{ 
    NSString *jsReplaceLinkCode = 
     @"document.body.innerHTML = " 
     @"document.body.innerHTML.replace(" 
      @"/(\\b(https?):\\/\\/[-A-Z0-9+&@#\\/%?=~_|!:,.;]*[-A-Z0-9+&@#\\/%=~_|])/ig, " 
      @"\"<a href='$1'>$1</a>\"" 
    @");"; 

    [webVew stringByEvaluatingJavaScriptFromString:jsReplaceLinkCode]; 
} 

Aquí está la llamada de JavaScript en un no Objective-C NSString cita versión:

document.body.innerHTML = document.body.innerHTML.replace(
     /(\b(https?):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, 
     "<a href='document.location=$1'>$1</a>" 
); 

La expresión regular no es perfecto, pero atrapará la mayoría de los enlaces.

+0

Esto funcionará perfecto. Nunca pensé en usar Javascript. –

+1

Puede ser lento con js, y también mi solución obj-c. –

+0

En este caso, si usamos la expresión regular dos veces, se agrega el mismo enlace link se puede agregar otra

0

Puede usar stringByReplacingOccurrencesOfString:withString: para buscar su match y reemplazarlo con el enlace HTML.

NSString *htmlTweet = [tweet stringByReplacingOccurrencesOfString:match withString:html]; 

(Usted puede también utilizar el rango que se obtiene de rangeOfFirstMatchInString:options:range en stringByReplacingCharactersInRange:withString: pero no estoy seguro de lo que sucede eso se pasa una cadena que superan la longitud varía en este caso).

Tenga en cuenta que su búsqueda solo encontrará el primer enlace en un tweet, y si hay varias coincidencias, las echará de menos.

+0

¡Gracias por su rápida respuesta! Usted tiene un punto válido acerca de cómo encontrar el primer enlace y debería modificar mi código. –

Cuestiones relacionadas