Matching a string and extracting values using regex

While I was working on Improving Facebook Integration for Social Paster, I was getting in response for an api call, a plain string containing access token. The string looked something like

access_token=1123243423442352453453&expires=32423553

In order to fetch values of access_token and expires I decided to use regex. All I needed to do was

var regex *regexp.Regexp
regex, err = regexp.Compile(`access_token=([^&]+)(?:&expires=(.*))?`)
matches := regex.FindStringSubmatch(responseString)
accessToken := matches[1]
expires := matches[2]

I got my accessToken and expires values rather easily!

Update : For a better solution to this Problem see comment

For more details on regex package in golang refer here

~~ Whizdumb ~~
Email : sachin.xpert@gmail.com

2 responses

  1. If tomorrow the query contains another item after expires (access_token=1234&expires=5678&new_item=90ab), your code will break.

    You’re handling the query portion of a url. It may be beneficial to use code that knows how to deal with queries:

    package main

    import (
    “fmt”
    “net/url”
    )

    func main() {
    query := “access_token=1123243423442352453453&expires=32423553&new_item=abcd”
    values, err := url.ParseQuery(query)
    if err != nil {
    panic(err)
    }
    fmt.Printf(“access_token = %v – expires = %v – new_item = %v – notexist = %v\n”,
    values.Get(“access_token”), values.Get(“expires”), values.Get(“new_item”), values.Get(“notexist”))
    }

    • Thanks! I had no idea about query parser. I was just looking around string functions. Cool!

Comments are closed.