NSString to NSDictionary - ios

I have a string (from HTTP Header) and want to split it into a dictionary.
foo = \"bar\",baz=\"fooz\", beta= \"gamma\"
I ca not guarantee that the string is the same every time. Maybe there are spaces, maybe not, sometimes the double quotes are escaped, sometimes not.
So I found the solution in PHP with regular expressions. Unfortunately I can't convert it to work on iOS.
preg_match_all('#('.$key.')=(?:([\'"])([^\2]+?)\2|([^\s,]+))#', $input, $hits, PREG_SET_ORDER);
foreach ($hits as $hit) {
$data[hit[1]] = $hit[3] ? $hit[3] : $hit[4];
}
Can anybody help me converting this to Objective-C?

I met a guy which is kinda RegEx guru. He explained the whole stuff and I got the following (working!!!!) solution in RegEx.
This gives me strings like foo="bar":
(?<=[,\\s])((realm|qop|nonce|opaque)=(?:([\"'])([^\2]+?)\2|([^\\s,]+)))
I then use another RegEx to split it by key and value to create a dictionary.

Related

Convert UTF string to Chinese Language from JSON response

I tried everything to convert JSON response to Chinese language but not getting any success. I need to display those string in uilabel.
This is the response I'm getting:
sentence = "\U00e6\U201a\U00a8\U00e5\U00a5\U00bd\U00e3\U20ac\U201a";
pinyin = "n\U00c3\U00adn h\U00c4\U0192o"
Converting sentence's string should be like 您好 but I'm getting 您好。
For pinyin I'm getting exactly right string [[nín hăo]] in label without converting but for sentence it gives me wrong value.
I'm using XCode 7.1 and my deployment target is 8.0.
Hi thanks all for helping and trying :) i ended up solving my own problem. What I did is directly put dict value to label text rather than passing from NSString. Taking it into string will give me value like 您好。
Here is what i've done.
cell.lblWord.text = [NSString stringWithFormat:#"Word: %#",[[dic objectForKey:#"cat"]objectForKey:#"chart"]];
It's strange but true, tried before but wasn't working.

Getting an XML value from an NSArray

I'm currently using SMXMLDocument as my parser and so far it does a fantastic job parsing some XML files. The only problem that I have encountered is that it cannot seem to handle children with the same name, well at least in my case. But this parser can return the parsed XML as an NSArray.
The NSArray would look like this:
(
"<id>https://spreadsheets.goog\U2026</id>",
"<updated>2013-12-23T17:54:04.814Z</updated>",
"<category term=\"http://schemas.google.com/spreadsheets/2006#cell\" scheme=\"http://schemas.google.com/spreadsheets/2006\"/>",
"<title type=\"text\">A1</title>",
"<content type=\"text\">What?</content>",
"<link rel=\"self\" type=\"application/atom+xml\" href=\"https://spreadsheets.google.com/feeds/cells/some key/od6/private/full/R1C1\"/>",
"<link rel=\"edit\" type=\"application/atom+xml\" href=\"https://spreadsheets.google.com/feeds/cells/some key/18o84x\"/>",
"<cell row=\"1\" col=\"1\" inputValue=\"What?\">What?</cell>",
"<id>A1</id>",
"<status code=\"200\" reason=\"Success\"/>",
"<operation type=\"update\"/>")
So my question is, how would I get the values (and attributes) from the XML? If there is a way to tokenize this (ie going through the array as an NSString with a for-in loop or something) without having to use a big fancy library that would be great. Thanks in advance.
Update:
Here is the NSLog of what happens if I try to get id with SMXMLDocument:
Code:
SMXMLElement* testEntry = [feed childNamed:#"entry"];
NSLog(#"id: %#", [testEntry valueWithPath:#"id"]);
Output:
id: https://spreadsheets.google.com/feeds/cells/some key/od6/private/full/R1C1
After hours of battling with the code, I ended up using another parser (as a secondary) called SHXMLParser because of it's neat syntax. It is capable returning multiple values from nodes with the same name as an NSArray. From there I just compared the contents in the array and picked the one I wanted.

How can I remove the quotation mark and commas?

I have a date in "12/5/24" format and I am trying to use it in a JavaScript function.
How can I use the date with no quotation marks and with commas?:
Date.UTC(12,5,24)
This is what I am trying to achieve:
date = "12/5/24"
var = date.some_method #=> 12,5,24
Date.UTC(var)
Write as below :
string = "12/5/24"
Date.UTC(*string.split('/').map(&:to_i))
date_array = "12/5/24".split("/").collect(&:to_i)
Date.UTC(date_array[0], date_array[1], date_array[2])
All the split and gsub answers are "wrong", because they fit the anti-pattern "cause the bug, then fix the bug." (Yet they are not "completely wrong", because sometimes that anti-pattern is unfortunately the simplest option!)
Use Time.parse(date).strftime('%m,%d,%y'). That's why you have to escape each y token in a time template with a percent % - so you have a whole string to play with, and can put anything else in it. You could even put the rest of your Javascript in there.
Date.UTC( *"12/5/24".split('/') )

string manipulation in ruby on rails

I have a string of the format,
/d.phpsoft_id=369242&url=http://f.1mobile.com/mobile_software/finance/com.mshift.android.achieva_2.apk
and i need to edit this string using regular expression that the result string should start from http: ie the resultatnt string should be
http://f.1mobile.com/mobile_software/finance/com.mshift.android.achieva_2.apk
please help
For these types of situations, I prefer to go with readily available tools that will help provide a solution or at the very least will point me in the right direction. My favourite for regex is txt2re because it will output example code in many languages, including ruby.
After running your string through the parser and selecting httpurl for matching, it output:
txt='/d.phpsoft_id=369242&url=http://f.1mobile.com/mobile_software/finance/com.mshift.android.achieva_2.apk'
re1='.*?' # Non-greedy match on filler
re2='((?:http|https)(?::\\/{2}[\\w]+)(?:[\\/|\\.]?)(?:[^\\s"]*))' # HTTP URL 1
re=(re1+re2)
m=Regexp.new(re,Regexp::IGNORECASE);
if m.match(txt)
httpurl1=m.match(txt)[1];
puts "("<<httpurl1<<")"<< "\n"
end
str = "/d.phpsoft_id=369242&url=http://f.1mobile.com/mobile_software/finance/com.mshift.android.achieva_2.apk"
str.spl­it("url=")­[1]
Simple Answer
You need to do following
str = "/d.phpsoft_id=369242&url=http://f.1mobile.com/mobile_software/finance/com.mshift.android.achieva_2.apk"
start=str.index('http://')
resultant=str[start,str.length]

NSString componentsSeparatedByString "&" but ignore "& amp;"

Need to separate a string on & but not on &.
Is there a more elegant way to code this up rather than just replacing it first then separating it on the &? Like this...
query = [query stringByReplacingOccurrencesOfString:#"&" withString:#"~~~"];
NSArray * kvpairs = [query componentsSeparatedByString:#"&"];
NSMutableArray *mArr = [[NSMutableArray alloc] init];
for (NSString *kvp in kvpairs) {
[mArr addObject:[kvp stringByReplacingOccurrencesOfString:#"~~~" withString:#"&"]];
}
kvpairs = [NSArray arrayWithArray:mArr];
[mArr release];
You could use NSRegularExpression to enumerate through the string on a regular expression that matches & but not &, e.g.: #"&(?!amp;)". This will be more cumbersome than your current method but more exact, because it will work without modifying the original string and doesn't rely on a token value.
If you control the input to this method and can guarantee that ~~~ won't appear normally, there's nothing wrong with using ~~~. However if you don't control the input then you should attempt to parse the string without modification.
There isn't really anything wrong with that, as long as you are 100% sure that the string ~~~ won't occur in your query.
If you are not, my next step would be to implement a method to parse the string into an array. In this method, you could find each &, then check if it is followed by amp;. If it is, move on to the next one, if it is not, cut the string there and repeat.
HTML entities and references are really not a good thing to have hanging around in URLs. Unless there is a very good reason that HTML entities must be used, I would recommend using '%26' in the URL encode an ampersand.
That being said, you will run into problems if '&' is not the only HTML entity or reference, so unless you are absolutely sure '&' is the only one, you will need a more robust solution.

Resources