Search for a string between two known strings

青春壹個敷衍的年華 提交于 2019-12-09 00:27:21

问题


I have a String with this content:

href="http://www.website.com/" /> [...] [...]

I just want to get the central part of the string. How is it possible to get the part between @"href="" and @"" />"

Note: Even if it looks like xml-code, it is inside of a NSString.


回答1:


I got it!

This is the code (not very nice written):

NSRange rr2 = [content rangeOfString:@"href=\""];
    NSRange rr3 = [content rangeOfString:@"\" />"];
    int lengt = rr3.location - rr2.location - rr2.length;
    int location = rr2.location + rr2.length;
    NSRange aa;
    aa.location = location;
    aa.length = lengt;
    theString = [theString substringWithRange:aa];



回答2:


How about

NSString* newNSString =[[[theString substringFromIndex:6] componentsSeparatedByString:@"/\""]objectAtIndex:0];

Or

NSString* newNSString =[[[[theString componentsSeparatedByString:@"href=\""]objectAtIndex:1] componentsSeparatedByString:@"/\""]objectAtIndex:0];



回答3:


This can be done more compactly:

NSRange end = [source rangeOfString:@"\" />"];
if (end.location != NSNotFound) {
    result = [source substringWithRange:NSMakeRange(6, end.location - 6)];
}


来源:https://stackoverflow.com/questions/2493153/search-for-a-string-between-two-known-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!