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.
Related
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
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+
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
I have to initialize string as "Rose" including Quotation Mark. How to write " in our string?
Escape the double quote with \
NSString *yourString = #"\"Rose\"";
Use the escape character: \
NSString *r = #"\"Rose\"";
You can find additional information about Escape character and String literal.
Escape it with a backslash:
#"\"Rose\""
Escape the quotation marks.
Example:
NSString *str = #"\"Rose\"";
NSString *yourString = #"\"Rose\"";
In swift 5, you can write with a hashtag :
let raw = #"You can create "raw" strings in Swift 5."#
Output :
You can create "raw" strings in Swift 5.
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...