How to parse numbers from NSString? - iphone

NSString *numberVector = #"( 1, 2, 3, 4)";
I want to get NSMutableArray from these numbers.
How can I do this?

This is the simpler one, convert it to json string first then convert is to array using NSJSONSerialization
NSString *numberVector = #"( 1, 2, 3, 4)";
numberVector = [numberVector stringByReplacingOccurrencesOfString:#"(" withString:#"["];
numberVector = [numberVector stringByReplacingOccurrencesOfString:#")" withString:#"]"];
NSError* error;
NSMutableArray *arr = [NSJSONSerialization JSONObjectWithData:[numberVector dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&error];
Update
This will work for both #"( 1, 2, 3, 4)" and #"(\n 1,\n 2,\n 3,\n 4\n)" as json string can have new line and spaces.
P.S This will work for iOS 5.0 or greater for other iOS you can use SBJSON or other parsing library available.

If you know that this is exactly your format and don't have to be flexible in the amount of spaces, brackets or commas:
NSCharacterSet *trimSet = [NSCharacterSet characterSetWithCharactersInString:#" ()"];
numberVector = [numberVector stringByTrimmingCharactersInSet:trimSet];
NSArray *numbers = [numberVector componentsSeparatedByString:#", "];

try like this it'l works fine for any type of data it accepts only numbers.
NSString *numberVector = #"(\n 1,\n 2,\n 3,\n 4\n)";
NSString *onlyNumbers = [numberVector stringByReplacingOccurrencesOfString:#"[^0-9,]" withString:#"" options:NSRegularExpressionSearch range:NSMakeRange(0, [numberVector length])];
NSArray *numbers=[onlyNumbers componentsSeparatedByString:#","];
NSLog(#"%#",numbers);

See the code below, it should work:
NSCharacterSet *cSet = [NSCharacterSet characterSetWithCharactersInString:#" ()"];
numberVector = [numberVector stringByTrimmingCharactersInSet:cSet];
//specify delimiter below
NSArray *numbers = [numberVector componentsSeparatedByString:#", "];

With this:
NSString *numberVector = #"( 1, 2, 3, 4)";
EDIT
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"&([^;])*;" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *modifiedString = [numberVector stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:#""];
NSArray *listItems = [[modifiedString stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]] componentsSeparatedByString:#", "]

Related

finding the index/position of a character in the URL format

I have the following url:
http://test.me/s/hq6aN
I basically wanted to replace that s with an d, what is the best way to do this using NSRegularExpression easily? Essentially what I want is to figure out the index of the /s/ in a string any idea how?
Here's what I have so far:
NSString *regexStr = #"/s/";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:0 error:&error];
NSArray *matches = [regex matchesInString:shortLink options:0 range:NSMakeRange(0, [shortLink length])];
if ([matches count] > 0){
NSTextCheckingResult *matchesIndex = [matches objectAtIndex:0];
NSRange range = matchesIndex.range;
}
I am pretty sure I am doing something wrong with the regexStr
Your pattern looks fine, but there's a convenience method for doing search-and-replace that allows you to write this much more succinctly:
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"/s/" options:0 error:&error];
NSMutableString *haystack = [NSMutableString stringWithString:#"http://test.me/s/hq6aN"];
[regex replaceMatchesInString:haystack options:0 range:NSMakeRange(0, [haystack length]) withTemplate:#"/d/"];
There is an equivalent -stringByReplacingMatchesInString:options:range:withTemplate: for NSStrings if you'd prefer to keep the string containing the original URL immutable.

Change parts of an NSString

I have a urlString that is: http://www.youtube.com/watch?v=5kdEhVtNFPo
I want to be able to change it into this: http://www.youtube.com/v/5kdEhVtNFPo
How would I go about doing that? I'm not sure if I should use the instance methods substringWithRange: or substringFromIndex:
I tried this which removes the first part and just leaves the video id (it removes http://www.youtube.com/watch?v=) now I just need to add http://www.youtube.com/v/ to the start of the string.
NSString *newUrlString = [urlString substringFromIndex:31];
NSString* newUrl = [oldUrl stringByReplacingOccurrencesOfString:#"watch?v=" withString:#"v/"];
Please note that this only works as long as the URL won't contain more instances of the string "watch?v=".
I'll propose a different way that may be more flexible on the inputs you give it:
- (NSString) newURLStringForOldURLString:(NSString *)oldURLString
{
NSString *newURLString = nil;
NSURL *url = [[NSURL alloc] initWithString:oldURLString];
NSString *query = [url query]; /* v=5kdEhVtNFPo */
NSArray *fieldValuePairs = [query componentsSeparatedByString:#"&"];
for (NSString *pair in fieldValuePairs) {
NSArray *components = [pair componentsSeparatedByString:#"="];
NSString *field = [components objectAtIndex:0];
NSString *value = [components objectAtIndex:1];
if ([field isEqualToString:#"v"]) {
newURLString = [NSString stringWithFormat:#"%#://%#:%#/%#/%#", [url scheme], [url domain], [url port], field, value];
break;
}
}
[url release];
return newURLString;
}
To be flexible enough, you could use NSRegularExpression:
NSString *str = #"http://www.youtube.com/watch?v=5kdEhVtNFPo";
NSString *pattern = #"((?:http:\\/\\/){0,1}www\\.youtube\\.com\\/)watch\\?v=([:alnum:]+)";
NSString *template = #"$1v/$2";
NSRegularExpression *regexp = [NSRegularExpression
regularExpressionWithPattern:pattern
options:NSRegularExpressionCaseInsensitive
error:nil];
NSString *newStr = [regexp stringByReplacingMatchesInString:str
options:0 range:NSMakeRange(0, [str length]) withTemplate:template];
NSLog(#"Replaced: %#", newStr);
Another alternative :
NSString *str3 = #"http://www.youtube.com/watch?v=5kdEhVtNFPo";
NSString *outputString;
NSRange range = [str3 rangeOfString:#"watch?v="];
if(range.location != NSNotFound)
{
outputString = [str3 stringByReplacingCharactersInRange:range withString:#"v/"];
NSLog(#"%#",outputString);
}

NSRegularExpression searching for unknown value

So I am working on an iPhone app, and it takes a picture of some text, the picture gets OCR'ed and sent back to me, and I then I use a regular expression to search the string for double values up to xxxx.xx.
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:#"\\d?\\d?\\d?\\d?\\.\\d?\\d?"
options:0
error:&error];
NSRange range = [regex rangeOfFirstMatchInString:result
options:0
range:NSMakeRange(0, [result length])];
if([result length] > 0)
{
NSString *subString = [result substringWithRange:range];
double r = [subString doubleValue];
Right now it is working as I want, but it only gets the first number it comes to. There could be an indeterminate number of doubles, and I need to get the largest one. What would be the best way to go about that?
Use matchesInString:options:range: instead of rangeOfFirstMatchInString. This will give you an array of NSTextCheckingResult objects, from which you can extract the range.
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:#"\\d?\\d?\\d?\\d?\\.\\d?\\d?"
options:0
error:&error];
NSArray *arr = [regex matchesInString:string options:NSMatchingReportCompletion range:NSMakeRange(0,string.length)];
for (NSTextCheckingResult *obj in arr) {
double r = [[string substringWithRange:obj.range] doubleValue];
NSLog(#"%f",r);
}

Why doesn't stringByReplacingPercentEscapesUsingEncoding: convert L%C3%A9on back to Léon?

I have the following:
modifiedTitle = #"Léon";
modifiedTitle = [modifiedTitle stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"%#", modifiedTitle);
Converted, it now shows as L%C3%A9on.
When I run the following it doesn't convert it back:
NSMutableString *searchText = [NSMutableString stringWithString:modifiedTitle];
[searchText stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"%#", searchText);
It still shows as L%C3%A9on.
Anyone know why?
Because stringByReplacingPercentEscapesUsingEncoding: returns a new string. Try this:
NSMutableString *searchText = [NSMutableString stringWithString:modifiedTitle];
NSString *newText = [searchText stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"%#", newText);

regular expressions iphone

How can I chceck on iPhone with regularexpressions NSStrring contain only this chars: a-zA-Z numbers 0-9 or specialchars: !##$%^&*()_+-={}[]:"|;'\<>?,./
NSCharacterSet *charactersToRemove = [[NSCharacterSet characterSetWithCharactersInString:#"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 "] invertedSet];
NSString *stringValueOfTextField = [[searchBar.text componentsSeparatedByCharactersInSet:charactersToRemove]
componentsJoinedByString:#""];
try this::::
For this purposes you can use standard class NSRegularExpression
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:#"\w[!##$%^&*()_+-={}\[\]:\"|;'\<>?,./]"
options:NSRegularExpressionCaseInsensitive
error:&error];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:string
options:0
range:NSMakeRange(0, [string length])];
Note that NSRegularExpression is only available on iOS 4 and above.