Formatting an String - iphone

I have an output string in this format .
I need to format the string such that i can display the URL separately and my Content, the description separately. Is there any functions , so i can format them easily ?
The code :
NSLog(#"Description %#", string);
The OUTPUT String:
2013-07-28 11:13:59.083 RSSreader[4915:c07] Description
http://www.apple.com/pr/library/2013/07/23Apple-Reports-Third-Quarter-Results.html?sr=hotnews.rss
Apple today announced financial results for its fiscal 2013 third quarter ended
June 29, 2013. The Company posted quarterly revenue of $35.3 billion and quarterly
net profit of $6.9 billion, or $7.47 per diluted share.
Apple sold 31.2 million iPhones, which set a June quarter record.

You should extract URL from string, then display it in formatted way.
A simple way to extracting URL is regular expressions (RegEX).
After extracting URL you can replace it with nothing:
str = [str stringByReplacingOccurrencesOfString:extractedURL
withString:#""];
You can use this :
https://stackoverflow.com/a/9587987/305135

If description string separated by line break (\n), you can do this:
NSArray *items = [yourString componentsSeparatedByString:#"\n"];

Regex is a good idea.
But there is a default way of detecting URLs within a String in Objective C, NSDataDetector.
NSDataDetector internally uses Regex.
NSString *aString = #"YOUR STRING WITH URLs GOES HERE"
NSDataDetector *aDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
NSArray *theMatches = [aDetector matchesInString:aString options:0 range:NSMakeRange(0, [aString length])];
for (int anIndex = 0; anIndex < [theMatches count]; anIndex++) {
// If needed, Save this URL for Future Use.
NSString *anURLString = [[[theMatches objectAtIndex:anIndex] URL] absoluteString];
// Replace the Url with Empty String
aTitle = [aTitle stringByReplacingOccurrencesOfString:anURLString withString:#""];
}

Related

How to replace occurrences of multiple strings with multiple other strings [NSString]

NSString *string = [myString stringByReplacingOccurrencesOfString:#"<wow>" withString:someString];
I have this code. Now suppose my app's user enters two different strings I want to replace with two different other strings, how do I achieve that? I don't care if it uses private APIs, i'm developing for the jailbroken platform. My user is going to either enter or or . I want to replace any occurrences of those strings with their respective to-be-replaced-with strings :)
Thanks in advance :P
Both dasblinkenlight’s and Matthias’s answers will work, but they both result in the creation of a couple of intermediate NSStrings; that’s not really a problem if you’re not doing this operation often, but a better approach would look like this.
NSMutableString *myStringMut = [[myString mutableCopy] autorelease];
[myStringMut replaceOccurrencesOfString:#"a" withString:somethingElse];
[myStringMut replaceOccurrencesOfString:#"b" withString:somethingElseElse];
// etc.
You can then use myStringMut as you would’ve used myString, since NSMutableString is an NSString subclass.
The simplest solution is running stringByReplacingOccurrencesOfString twice:
NSString *string = [[myString
stringByReplacingOccurrencesOfString:#"<wow>" withString:someString1]
stringByReplacingOccurrencesOfString:#"<boo>" withString:someString2];
I would just run the string replacing method again
NSString *string = [myString stringByReplacingOccurrencesOfString:#"foo" withString:#"String 1"];
string = [string stringByReplacingOccurrencesOfString:#"bar" withString:#"String 2"];
This works well for me in Swift 3.1
let str = "hi hello hey"
var replacedStr = (str as NSString).replacingOccurrences(of: "hi", with: "Hi")
replacedStr = (replacedStr as NSString).replacingOccurrences(of: "hello", with: "Hello")
replacedStr = (replacedStr as NSString).replacingOccurrences(of: "hey", with: "Hey")
print(replacedStr) // Hi Hello Hey

How to extract email address from string using NSRegularExpression

I am making an iphone application. I have a scenario where i have a huge string, which has lot of data, and i would like to extract only email addresses from the string.
For example if the string is like
asdjasjkdh asdhajksdh jkashd sample#email.com asdha jksdh asjdhjak sdkajs test#gmail.com
i should extract "sample#email.com" and "test#gmail.com"
and i also want to extract only date, from the string
For example if the string is like
asdjasjkdh 01/01/2012 asdhajksdh jkas 12/11/2012 hd sample#email.com asdha jksdh asjdhjak sdkajs test#gmail.com
i should extract "01/01/2012" and "12/11/2012"
A small code snipet, will be very helpful.
Thanks in advance
This will do what you want:
// regex string for emails (feel free to use a different one if you prefer)
NSString *regexString = #"([A-Za-z0-9_\\-\\.\\+])+\\#([A-Za-z0-9_\\-\\.])+\\.([A-Za-z]+)";
// experimental search string containing emails
NSString *searchString = #"asdjasjkdh 01/01/2012 asdhajksdh jkas 12/11/2012 hd sample#email.com asdha jksdh asjdhjak sdkajs test#gmail.com";
// track regex error
NSError *error = NULL;
// create regular expression
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexString options:0 error:&error];
// make sure there is no error
if (!error) {
// get all matches for regex
NSArray *matches = [regex matchesInString:searchString options:0 range:NSMakeRange(0, searchString.length)];
// loop through regex matches
for (NSTextCheckingResult *match in matches) {
// get the current text
NSString *matchText = [searchString substringWithRange:match.range];
NSLog(#"Extracted: %#", matchText);
}
}
Using your sample string above:
asdjasjkdh 01/01/2012 asdhajksdh jkas 12/11/2012 hd sample#email.com asdha jksdh asjdhjak sdkajs test#gmail.com
The output is:
Extracted: sample#email.com
Extracted: test#gmail.com
To use the code, just set searchString to the string you want to search. Instead of the NSLog() methods, you'll probably want to do something with the extracted strings matchText. Feel free to use a different regex string to extract emails, just replace the value of regexString in the code.
NSArray *chunks = [mylongstring componentsSeparatedByString: #" "];
for(int i=0;i<[chunks count];i++){
NSRange aRange = [chunks[i] rangeOfString:#"#"];
if (aRange.location !=NSNotFound) NSLog(#"email %#",chunks[i] );
}
You can use this regex to match emails
[^\s]*#[^\s]*
and this regex to match dates
\d+/\d+/\d+

regular expression to match " but not \"

How can I construct a regular expression which matches an literal " but only if it is not preceded by the escape slash namely \
I have a NSMutableString str which prints the following on NSLog. The String is received from a server online.
"Hi, check out \"this book \". Its cool"
I want to change it such that it prints the following on NSLog.
Hi, check out "this book ". Its cool
I was originally using replaceOccurencesOfString ""\" with "". But then it will do the following:
Hi, check out \this book \. Its cool
So, I concluded I need the above regular expression to match only " but not \" and then replace only those double quotes.
thanks
mbh
[^\\]\"
[^m] means does not match m
Not sure how this might translate to whatever is supported in the iOS apis, but, if they support anchoring (which I think all regex engines should), you're describing something like
(^|[^\])"
That is, match :
either the beginning of the string ^ or any character that's not
\ followed by:
the " character
If you want to do any sort of replacement, you'll have to grab the first (and only) group in the regex (that is the parenthetically grouped part of the expression) and use it in the replacement. Often this value labeled as $1 or \1 or something like that in your replacement string.
If the regex engine is PCRE based, of course you could put the grouped expression in a lookbehind so you wouldn't need to capture and save the capture in the replacement.
Not sure about regex, a simpler solution is,
NSString *str = #"\"Hi, check out \\\"this book \\\". Its cool\"";
NSLog(#"string before modification = %#", str);
str = [str stringByReplacingOccurrencesOfString:#"\\\"" withString:#"#$%$#"];
str = [str stringByReplacingOccurrencesOfString:#"\"" withString:#""];
str = [str stringByReplacingOccurrencesOfString:#"#$%$#" withString:#"\\\""];//assuming that the chances of having '#$%$#' in your string is zero, or else use more complicated word
NSLog(#"string after modification = %#", str);
Output:
string before modification = "Hi, check out \"this book \". Its cool"
string after modification = Hi, check out \"this book \". Its cool
Regex: [^\"].*[^\"]. which gives, Hi, check out \"this book \". Its cool
It looks like it's a JSON string? Perhaps created using json_encode() in PHP on the server? You should use the proper JSON parser in iOS. Don't use regex as you will run into bugs.
// fetch the data, eg this might return "Hi, check out \"this book \". Its cool"
NSData *data = [NSData dataWithContentsOfURL:#"http://example.com/foobar/"];
// decode the JSON string
NSError *error;
NSString *responseString = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
// check if it worked or not
if (!responseString || ![responseString isKindOfClass:[NSString class]]) {
NSLog(#"failed to decode server response. error: %#", error);
return;
}
// print it out
NSLog(#"decoded response: %#", responseString);
The output will be:
Hi, check out "this book ". Its cool
Note: the JSON decoding API accepts an NSData object, not an NSString object. I'm assuming you also have a data object and are converting it to a string at some point... but if you're not, you can convert NSString to NSData using:
NSString *responseString = [NSJSONSerialization JSONObjectWithData:[myString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:&error];
More details about JSON can be found at:
http://www.json.org
http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html

Apply regular expression repeatedly

I've got text expressions like this:
HIUPA:bla1bla1'HIUPD:bla2bla2'HIUPD:bla3bla3'HISYN:bla4bla4'
I want to extract the following text pieces:
HIUPD:bla2bla2'
And
HIUPD:bla3bla3'
My Objective-C code for this looks like this:
-(void) ermittleKonten:(NSString*) bankNachricht
{
NSRegularExpression* regexp;
NSTextCheckingResult* tcr;
regexp = [NSRegularExpression regularExpressionWithPattern:#"HIUPD.*'" options:0 error:nil];
int numAccounts = [regexp numberOfMatchesInString:bankNachricht options:0 range:NSMakeRange(0, [bankNachricht length])];
for( int i = 0; i < numAccounts; ++i ) {
tcr = [regexp firstMatchInString:bankNachricht options:0 range:NSMakeRange( 0, [bankNachricht length] )];
NSString* HIUPD = [bankNachricht substringWithRange:tcr.range];
NSLog(#"Found text is:\n%#", HIUPD);
}
}
In the Objective-C code numAccounts is 1, but should be 2. And the string that is found is "HIUPD:bla2bla2'HIUPD:bla3bla3'HISYN:bla4bla4'"
I tested the regular expression pattern with an online tool ( http://www.regexplanet.com/simple/index.html ). In the online tool it works fine and delivers 2 results as I want it to be.
But I would like to have the same result in the ios code, i.e. "HIUPD:bla2bla2'" and "HIUPD:bla3bla3'". What is wrong with the pattern?
You're doing greedy matching with the .*, so the regular expression catches as much as it can in the .*. You should be doing .*?, or [^']*, so that the * can't match a '.

How to Convert NSInteger or NSString to a binary (string) value

Anybody has some code in objective-c to convert a NSInteger or NSString to binary string?
example:
56 -> 111000
There are some code in stackoverflow that try do this, but it doesn´t work.
Thanks
Not sure which examples on SO didn't work for you, but Adam Rosenfield's answer here seems to work. I've updated it to remove a compiler warning:
// Original author Adam Rosenfield... SO Question 655792
NSInteger theNumber = 56;
NSMutableString *str = [NSMutableString string];
for(NSInteger numberCopy = theNumber; numberCopy > 0; numberCopy >>= 1)
{
// Prepend "0" or "1", depending on the bit
[str insertString:((numberCopy & 1) ? #"1" : #"0") atIndex:0];
}
NSLog(#"Binary version: %#", str);
Tooting my own horn a bit here...
I've written a math framework called CHMath that deals with arbitrarily large integers. One of the things it does is allows the user to create a CHNumber from a string, and get its binary representation as a string. For example:
CHNumber * t = [CHNumber numberWithString:#"56"];
NSString * binaryT = [t binaryStringValue];
NSLog(#"Binary value of %#: %#", t, binaryT);
Logs:
2009-12-15 10:36:10.595 otest-x86_64[21918:903] Binary value of 56: 0111000
The framework is freely available on its Github repository.