NSRegularExpression to extract text - iphone

All,
I have a dictionary with two keys and values. I need to extract bits and pieces from them and place them into seperate strings.
{
IP = "192.168.17.1";
desc = "VUWI-VUWI-ABC_Dry_Cleaning-R12-01";
}
That is what the dictionary looks like when I call description.
I want the new output to be like this:
NSString *IP = #"192.168.17.1";
NSString *desc = #"ABC Dry Cleaning"; //note: I need to get rid of the underscores
NSString *type = #"R";
NSString *num = #"12";
NSString *ident = #"01";
How would I achieve this?
I've read through the Apple developer docs on NSRegularExpression but I find it hard to understand. I'm sure once I get some help once here I can figure it out in the future, I just need to get started.
Thanks in advance.

Okay, so first, you have to get the object associated with each key:
NSString *ip = [dic objectForKey:#"IP"]; //Btw, you shouldn't start a variable's name with a capital letter.
NSString *tempDesc = [dic objectForKey:#"desc"];
Then, what I would do is split the string in tempDesc, based on the character -.
NSArray *tmpArray = [tempDesc componentsSeparatedByString:#"-"];
Then you just have to get the strings or substrings you're interested in, and reformat them as needed:
NSString *desc = [[tmpArray objectAtIndex:2] stringByReplacingOccurrencesOfString:#"_" withString:#" "];
NSString *type = [[tmpArray objectAtIndex:3] substringToIndex:1];
NSString *num = [[tmpArray objectAtIndex:3] substringFromIndex:1];
NSString *ident = [tmpArray objectAtIndex:4];
As you can see, this works perfectly without using NSRegularExpression.

Related

Parsing XML from NSString to get values

This question is for manipulating NSString in xcode.
I have a XML text string that I get from the web that looks like this
<current temperature="73" day="Mon" humidity="59" windspeed="10"></current>
How can I get individual values from this string and put them in my NSString variables?
e.g.
NSString *tempStr = ??
NSString *dayStr = ??
NSString *windspeedStr = ??
First, download and include RaptureXML within your project as described on the RaptureXML project site.
For parsing the single given line, use the following snippet - your input is passed as inXmlString;
//transform string into an XML DOM
RXMLElement *rootNode = [RXMLElement elementFromXMLString:inXmlString
withEncoding:NSUTF8StringEncoding];
if (rootNode == nil || ![rootNode isValid])
{
//do something, we failed!
}
else
{
NSString *temperature = [rootNode attribute:#"temperature"];
NSString *day = [rootNode attribute:#"day"];
NSString *windspeed = [rootNode attribute:#"windspeed"];
}
The basic idea is to use the NSString method componentsSeparatedByString: to parse out the data you want. You'll probably need to do a bit more work to get it exactly right for your scenario.
NSArray* paArray1= [pstrXMLString componentsSeparatedByString:#" "];
temlStr= [[[paArray1 objectAtIndex:1] componentsSeparatedByString:#"="] objectAtIndex:1];
dayStr= [[[paArray1 objectAtIndex:2] componentsSeparatedByString:#"="] objectAtIndex:1];
windspeedStr= [[[paArray1 objectAtIndex:3] componentsSeparatedByString:#"="] objectAtIndex:1];

Read from txt list file and set many objects in ios

I, I'm writing an application that has to read the content of txt.
this txt is such a property file with a list formatted in this way:
1|Chapter 1|30
2|Chapter AA|7
3|Story of the United States|13
........
keys are separated by "|".
I googled a lot hoping to find any "pragmatically solution" but nothing...
how can I read these informations and set many objects like:
for NSInterger *nChapter = the first element
for NSString *title = the second element
for NSInteger *nOfPages = the last element ?
NSString's - (NSArray *)componentsSeparatedByString:(NSString *)separator could be your best friend.
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/doc/uid/20000154-componentsSeparatedByString_
Only if you read NSString's class reference:
NSString *str = [NSString stringWithContentsOfFile:#"file.txt"];
NSArray *rows = [str componentsSeparatedByString:#"\n"];
for (NSString *row in rows)
{
NSArray *fields = [row componentsSeparatedByString:#"|"];
NSInteger nChapter = [[fields objectAtIndex:0] intValue];
NSString *title = [fields objectAtIndex:1];
// process them in here
}

How can I get an integer value from NSString in an iPhone application?

NSString * str=[zoneDict objectForKey:#"name"];
NSLog(#"==========string zone::==========%#",str);
// str="(GMT +3:00) Baghdad, Riyadh, Moscow, St. Petersbur";
How can I get the 3:00 value from the above string?
NSString *str = #"(GMT -3:00) Baghdad, Riyadh, Moscow, St. Petersbur";
NSRange endRange = [str rangeOfString:#")"];
NSString *timeString = [str substringWithRange:NSMakeRange(5, endRange.location-5)];
NSRange separatorRange = [timeString rangeOfString:#":"];
NSInteger hourInt = [[timeString substringWithRange:NSMakeRange(0, separatorRange.location)] intValue];
NSLog(#"Hour:%d",hourInt);
Rather than trying to extract the time offset from the string, is there any way you could store actual time zone data in your zoneDict? For example you could store NSTimeZone instances instead.
If all you have is the string, you could use an NSRegularExpression object and extract the relevant information using a regular expression instead.
If you could explain further what you're trying to do then there may be an alternative way to achieve what you want.
I like to use -[NSString componentsSeparatedByString]:
NSString *str = #"(GMT -3:00) Baghdad, Riyadh, Moscow, St. Petersbur";
NSArray *myWords = [myString componentsSeparatedByString:#")"];
NSString *temp1 = [myWords objectAtIndex:0];
if ([temp1 rangeOfString:#"-"].location == NSNotFound) {
NSArray *temp2 = [temp1 componentsSeparatedByString:#"+"];
NSString *temp3 = [temp2 objectAtIndex:1];
NSLog(#"Your String - %#", temp3);
}
else {
NSArray *temp2 = [temp1 componentsSeparatedByString:#"-"];
NSString *temp3 = [temp2 objectAtIndex:1];
NSLog(#"Your String - %#", temp3);
}
Output:
Your String - 3:00
Using regular expressions is the better option in my view (if you are forced to extract the '3' only). The regular expression string would contain something like "\d?" but don't quote me on that, you'll have to look up the exact string. Perhaps someone on here could provide the exact string.

Get last path part from NSString

Hi all i want extract the last part from string which is a four digit number '03276' i:e http://www.abc.com/news/read/welcome-new-gig/03276
how can i do that.
You can also use
NSString *sub = [#"http://www.abc.com/news/read/welcome-new-gig/03276" lastPathComponent];
If you know how many characters you need, you can do something like this:
NSString *string = #"http://www.abc.com/news/read/welcome-new-gig/03276";
NSString *subString = [string substringFromIndex:[string length] - 5];
If you just know that it's the part after the last slash, you can do this:
NSString *string = #"http://www.abc.com/news/read/welcome-new-gig/03276";
NSString *subString = [[string componentsSeparatedByString:#"/"] lastObject];
Since *nix uses the same path separators as URL's this will be valid as well.
[#"http://www.abc.com/news/read/welcome-new-gig/03276" lastPathComponent]
If you know the length of the number, and it's not gonna change, it can be as easy as:
NSString *result = [string substringFromIndex:[string length] - 4];
If the last part of the string is always the same length (5 characters) you could use this method to extract the last part:
- (NSString *)substringFromIndex:(NSUInteger)anIndex
Use the length of the string to determine the start index.
Something like this:
NSString *inputStr = #"http://www.abc.com/news/read/welcome-new-gig/03276";
NSString *newStr = [inputStr substringFromIndex:[inputStr length]-5];
NSLog(#"These are the last five characters of the string: %#", newStr);
(Code not tested)
NSString *str = #"http://www.abc.com/news/read/welcome-new-gig/03276";
NSArray *arr = [str componentSeparatedBy:#"gig/"];
NSString *strSubStringDigNum = [arr objectAtIndex:1];
strSubStringDigNum will have the value 03276
Try this:
NSString *myUrl = #"http://www.abc.com/news/read/welcome-new-gig/03276";
NSString *number = [[myUrl componentsSeparatedByString:#"/"] objectAtIndex: 5];

Split one string into different strings

i have the text in a string as shown below
011597464952,01521545545,454545474,454545444|Hello this is were the message is.
Basically i would like each of the numbers in different strings to the message eg
NSString *Number1 = 011597464952
NSString *Number2 = 01521545545
etc
etc
NSString *Message = Hello this is were the message is.
i would like to have that split out from one string that contains it all
I would use -[NSString componentsSeparatedByString]:
NSString *str = #"011597464952,01521545545,454545474,454545444|Hello this is were the message is.";
NSArray *firstSplit = [str componentsSeparatedByString:#"|"];
NSAssert(firstSplit.count == 2, #"Oops! Parsed string had more than one |, no message or no numbers.");
NSString *msg = [firstSplit lastObject];
NSArray *numbers = [[firstSplit objectAtIndex:0] componentsSepratedByString:#","];
// print out the numbers (as strings)
for(NSString *currentNumberString in numbers) {
NSLog(#"Number: %#", currentNumberString);
}
Look at NSString componentsSeparatedByString or one of the similar APIs.
If this is a known fixed set of results, you can then take the resulting array and use it something like:
NSString *number1 = [array objectAtIndex:0];
NSString *number2 = [array objectAtIndex:1];
...
If it is variable, look at the NSArray APIs and the objectEnumerator option.
NSMutableArray *strings = [[#"011597464952,01521545545,454545474,454545444|Hello this is were the message is." componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#",|"]] mutableCopy];
NString *message = [[strings lastObject] copy];
[strings removeLastObject];
// strings now contains just the number strings
// do what you need to do strings and message
....
[strings release];
[message release];
does objective-c have strtok()?
The strtok function splits a string into substrings based on a set of delimiters.
Each subsequent call gives the next substring.
substr = strtok(original, ",|");
while (substr!=NULL)
{
output[i++]=substr;
substr=strtok(NULL, ",|")
}
Here's a handy function I use:
///Return an ARRAY containing the exploded chunk of strings
///#author: khayrattee
///#uri: http://7php.com
+(NSArray*)explodeString:(NSString*)stringToBeExploded WithDelimiter:(NSString*)delimiter
{
return [stringToBeExploded componentsSeparatedByString: delimiter];
}