regular expression to match " but not \" - iphone

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

Related

how to remove \ from a word \"hello\" in objective c?

From webservice i get the data as json but the problem is the json comes with all " with a \ ie "all" comes as \"all\"
How to make this a valid json and then a dictionary?
{
GetDataResult = "[{\"www\":{\"0\":{\"ID\":\"10233\",\"Queue\":\"COMPLETED\",\"EstCommName\":\"\U062e\U0631\U0645 \U0644\U0644\U0627\U0644\U0648\U0645\U0646\U064a\U0648\U0645 \U0648\U0627\U0644\U0632\U062c\U0627\U062c\",\"ReturnTime\":\"\",\"Latitude\":\"\",\"Longitude\":\"\"},\"1\":{\"ID\":\"10304\",\"Queue\":\"COMPLETED\",\"EstCommName\":\"\U0627\U062d\U0645\U062f \U0627\U0644\U0643\U0646\U062f\U064a \U0644\U0644\U0627\U0644\U0645\U0648\U0646\U064a\U0648\U0645 \U0648\U0627\U0644\U0632\U062c\U0627\U062c\",\"ReturnTime\":\"\",\"Latitude\":\"\",\"Longitude\":\"\"},\"2\":{\"ID\":\"10667\",\"Queue\":\"FRESH\",\"EstCommName\":\"\U0645\U0646\U062c\U0631\U0629 \U0627\U0644\U062e\U0632\U0646\U0629\",\"ReturnTime\":\"\",\"Latitude\":\"\",\"Longitude\":\"\"},\"3\":{\"ID\":\"10777\",\"Queue\":\"FRESH\",\"EstCommName\":\"\U0645\U0624\U0633\U0633\U0647 \U062c\U0647\U0627\U0645 \U0644\U0627\U0639\U0645\U0627\U0644 \U0627\U0644\U0633\U064a\U0631\U0627\U0645\U064a\U0643\",\"ReturnTime\":\"\",\"Latitude\":\"\",\"Longitude\":\"\"}}},{\"asd\":{}},{\"ssd\":{}}]";
In other words
TLDR
how to remove \ from a word \"hello\".? ie output needed is "hello".
What i tried
NSLog(#"%#",[[op objectForKey:#"GetSampleDataResult"] stringByReplacingOccurrencesOfString:#"\"" withString:#""]);
I have not tried this but something like this can work for you.
Sample Code :
NSString *yourString = [yourJSON objectForKey:#"GetDataResult"];
NSData *data = [yourString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSArray *www = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSLog(#"www :: %#",www);
I tried like this below:--
NSString *word= #"'\'hello'\'";
NSArray *arr=[word componentsSeparatedByString:#"'\'"];
for (NSString *str in arr)
{
if ([str length] >0)
{
NSLog(#"%#",str);
}
}
from the top of my head, to replace \" you need to specify it as \\\"
reason being that \ itself is used as an escape character and thus you need to escape:
\ with \\
" with \"
but the quotes are needed so you need to rid yourself of the \
so this:
NSLog(#"%#",[[op objectForKey:#"GetSampleDataResult"]
stringByReplacingOccurrencesOfString:#"\\"
withString:#""]);
but as mentioned, NSJSONSerialization is the best way to go about this
[string stringByReplacingOccurrencesOfString:#"\\\"" withString:#"\""];
Be careful with quotation marks and backslashes.
Result of \\\" will be \", exactly what you need to find.
Result of \" will be ", exactly what you need to replace.
Edit: This is answer to “How to remove \ from a word \"hello\"?”, not a solution to the problem.

Formatting an String

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:#""];
}

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+

Error in json parsing while converting response into NSDictionary

AM getting below error while converting json response into NSdictionary in json parsing...
ERROR:-JSONValue failed. Error trace is: (
Error Domain=org.brautaset.JSON.ErrorDomain Code=3 UserInfo=0x4d38270 "Unrecognised leading character"
)
any suggestion...
You most likely have the same issue as me... The returning data is in JSONP format instead of pure JSON. In other words you will be dealing with something like
functionCall({"Name": "Foo", "Id" : 1234, "Rank": 7});
instead of just
{"Name": "Foo", "Id" : 1234, "Rank": 7}
More info here
You'll need to strip the function and parentheses from the string before parsing it through the JSON Framework. You can do that with the following Regular Expression (spaced out to make it easier to see):
\w+ \s? \( ( \{ .* \} ) \}
And the script to write this is:
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:#"\\w+\\s?\\((\\{.*\\})\\)"
options:NSRegularExpressionCaseInsensitive
error:&error];
[regex replaceMatchesInString:resultString
options:0
range:NSMakeRange(0, [resultString length])
withTemplate:#"$1"];
NSLog(#"resultString = %#", resultString);
NSLog(#"converted = %#", [resultString JSONValue]);
where resultString is the response from the url request... It has to be stored as an NSMutableString in order for the regex to update it.
actually am not creating the json object by using api am retrieving it..
now i found the reason for that error. am not giving valid json object to covert into nsdictionary...So for getting valid json object we have to produce valid url to retrieve json object.
thanks for your suggestion...

NSString: EOL and rangeOfString issues

Could someone please tell me if I am missing something here... I am trying to parse individual JSON objects out of a data stream. The data stream is buffered in a regular NSString, and the individual JSON objects are delineated by a EOL marker.
if([dataBuffer rangeOfString:#"\n"].location != NSNotFound) {
NSString *tmp = [dataBuffer stringByReplacingOccurrencesOfString:#"\n" withString:#"NEWLINE"];
NSLog(#"%#", tmp);
}
The code above outputs "...}NEWLINE{..." as expected. But if I change the #"\n" in the if-statement above to #"}\n", I get nothing.
Why don't you use - (NSArray *)componentsSeparatedByString:(NSString *)separator? You can give it a separator of #"\n" and the result will be a convenient array of strings representing your individual JSON strings which you can then iterate over.
if([dataBuffer rangeOfString:#"\n"].location != NSNotFound) {
NSArray* JSONstrings = [dataBuffer componentsSeparatedByString:#"\n"];
for(NSString* oneString in JSONstrings)
{
// here's where you process individual JSON strings
}
}
If you do mess with the terminating '}' you could make the JSON data invalid. Just break it up and pass it to the JSON library. There could easily be a trailing space after the '}' that is causing the problem you are observing.