tags:

views:

445

answers:

3

It's a bit late, but I'm disappointed in myself for not coming up with something more elegant. Anyone have a better way to do this...

When you pass an OAuth code to Facebook, it response with a query string containing access_token and expires values.

access_token=121843224510409|2.V_ei_d_rbJt5iS9Jfjk8_A__.3600.1273741200-569255561|TxQrqFKhiXm40VXVE1OBUtZc3Ks.&expires=4554

Although if you request permission for offline access, there's no expires and the string looks like this:

access_token=121843224510409|2.V_ei_d_rbJt5iS9Jfjk8_A__.3600.1273741200-569255561|TxQrqFKhiXm40VXVE1OBUtZc3Ks.

I attempted to write a regex that would suffice for either condition. No dice. So I ended up with some really ugly Ruby:

s = s.split("=")
@oauth = {}
if s.length == 3
  @oauth[:access_token] = s[1][0, s[1].length - 8]
  @oauth[:expires] = s[2]
else
  @oauth[:access_token] = s[1]
end

I know there must be a better way!

A: 

Split on the & symbol first, and then split each of the results on =? That's the method that can cope with the order changing, since it parses each key-value pair individually.

Alternatively, a regex that should work would be...

/access_token=(.*?)(?:&expires=(.*))/
Amber
chipotle_warrior
Amber
Amber
Sorry, failed to read your `split` directive. If you edit your answer (anything), I'll be able to vote it back up. Thanks.
chipotle_warrior
Sure thing, Ry. :)
Amber
+1  A: 

If the format is strict, then you use this regex:

access_token=([^&]+)(?:&expires=(.*))?

Then access_token value is in \1, and expires, if there's any, will be in \2.

polygenelubricants
chipotle_warrior
A: 

Query string parsing usually involves these steps:

  1. If it is a complete URL, take the part after the first ?
  2. split the rest on &
  3. for each of the resulting name=value pairs, split them on =
  4. URL-decode to the value and the name (!)
  5. stuff the result into a data structure of your liking

Using regex is possible, but makes invalid assumptions about the state of URL-encoding the string is in and fails if the order of the query string changes, which is perfectly allowed and therefore cannot be ruled out. Better to encapsulate the above in a little parsing function or use one of the existing URL-handling libraries of your platform.

Tomalak