[英]How to extract email address from string using NSRegularExpression
[英]How do I extract a specific part of a string with NSRegularExpression?
說我有很多不同的字符串:
"http://website.com/283/comments/einp43/2398/32/34/23/4/4"
"http://website.com/23283/l34/comments/inhd3/3928/3/2/3"
"http://website.com/pics/283/comments/en43/a89st/389238/a823/"
"http://website.com/pics/hd/283/comments/as87/asd7j/3"
我一直希望comments/
后面的部分是有價值的ID。 但是我不需要注釋部分,我只需要ID。
如何隔離/提取?
假設網站名稱存儲為NSString
名為websiteName
:
NSArray *components = [websiteName componentsSeparatedByString:@"comments/"];
NSString *valuableID = [components lastObject];
(編輯:直到發布此答案后,我才注意到標題中未提及NSRegularExpression
,但是在這種情況下,我不認為正則表達式是必需的,因為您正在尋找單個常量字符串並且不需要復雜的模式承認。)
您可以使用正則表達式進行操作,請嘗試以下代碼
NSString *string = @"http://website.com/23283/l34/comments/inhd3/3928/3/2/3";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"/comments/([^/]*)" options:NSRegularExpressionCaseInsensitive error:nil];
[regex enumerateMatchesInString:string options:0 range:NSMakeRange(0, string.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
NSString *subStr = [string substringWithRange:[result rangeAtIndex:1]];
NSLog(@"commentId = %@", subStr);
}];
輸出:
commentId = inhd3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.