Pregunta

I am having string like following.

<a href=\"http://www.google.com\" title=\"My Title\" target=\"_blank\">Link 1</a>

How will i get "href" and "Link1" substrings. I have tried,but i didn't get valid solution.Please share the solution.Thanks in advance.

¿Fue útil?

Solución

For fetching the URL from a string:

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 *someString = @"<a href=\"http://www.google.com\" title=\"My Title\" target=\"_blank\">Link 1</a>";

NSString *match = [someString substringWithRange:[expression rangeOfFirstMatchInString:someString options:NSMatchingCompleted range:NSMakeRange(0, [someString length])]];

NSLog(@"%@", match); // Correctly prints 'http://www.google.com'

for matching the text:

   NSRegularExpression *textRegex = [NSRegularExpression regularExpressionWithPattern:@"\>([^]]+)\<" options:NSRegularExpressionCaseInsensitive error:NULL];

NSString *someString = @"<a href=\"http://www.google.com\" title=\"My Title\" target=\"_blank\">Link 1</a>";

    NSString *match = [someString substringWithRange:[expression rangeOfFirstMatchInString:someString options:NSMatchingCompleted range:NSMakeRange(0, [someString length])]];

   NSLog(@"%@", match); // Correctly prints 'Link 1'

Hope you will be able to use it now

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top