Reputation: 1681
I would like to strip part of an NSString
.
in the following string I would like to just grab the digits before the "/sampletext1/sampletext2/sampletext3"
1464/sampletext1/sampletext2/sampletext3
I have already stripped out the web address before the digits, but can't figure out the rest. Sometimes the digits could be 3 or 4 or 5 digits long.
thanks
Upvotes: 0
Views: 651
Reputation: 27550
You mentioned that you extracted a web address from the front, so I'm guessing you're dealing with either something like http://localhost:12345/a/b/c
or http://localhost/12345/a/b/c
.
In either case, you can convert your string to an NSURL and take advantage of its built-in features:
// Port
NSURL *URL = [NSURL URLWithString:@"http://localhost:12345/a/b/c"];
NSUInteger port = URL.port.integerValue;
// Path component
NSURL *URL = [NSURL URLWithString:@"http://localhost/12345/a/b/c"];
NSString *number = URL.pathComponents[1];
Upvotes: 3
Reputation: 38162
Use regular expressions:
NSError *error;
NSString *test = @"1464/sampletext1/sampletext2/sampletext3";
NSRegularExpression *aRegex = [NSRegularExpression regularExpressionWithPattern:@"^\\d+"
options:NSRegularExpressionCaseInsensitive
error:&error];
NSRange aRangeOfFirstMatch = [aRegex rangeOfFirstMatchInString:test options:0 range:NSMakeRange(0, [test length])];
if (aRangeOfFirstMatch.location != NSNotFound) {
NSString *matchedString = [test substringWithRange:aRangeOfFirstMatch];
NSLog(@"matchedString = %@", matchedString);
}
Upvotes: 0
Reputation: 318814
Get the index of the first /
character then get the substring up to that location.
NSString *stuff = @"1464/sampletext1/sampletext2/sampletext3";
NSString *digits;
NSRange slashRange = [stuff rangeOfString:@"/"];
if (slashRange.location != NSNotFound) {
digits = [stuff substringToIndex:slashRange.location];
} else {
digits = stuff;
}
Upvotes: 6