Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save ja-k-e/425afbbd46e0cb2c22ea to your computer and use it in GitHub Desktop.

Select an option

Save ja-k-e/425afbbd46e0cb2c22ea to your computer and use it in GitHub Desktop.
Regex for the People: Valid JSON to CoffeeScript Object

###Initial String { "user": { "username": "jakealbaugh", "email": "jake@example.com" }, "number": 1 }

###Desired String user: username: "jakealbaugh" email: "jake@example.com" number: 1

###Goal 1: "Remove quotes from keys" ####Find Pattern "(.*)":

  • " finds beginning of JSON "key".
    • ( opens new capture group. contents represented by $1 in replace.
      • . any character except a new line
      • * preceding token zero to infinite times
    • ) closes capture group
  • " closes key
  • : mandates that the key must be immediately followed by a literal colon.
    • prevents value strings from being replaced

####Replace With $1:

  • replace with capture group and a literal colon

###Goal 2: "Remove end-of-line commas" ####Find Pattern ,\n

  • , finds instance of a comma.
  • \n finds new line. mandates that the prior comma is at the end of the line
    • prevents commas in value strings from being replaced
    • \: escapes following character. \n = new line, n = literal "n"

####Replace With \n

  • replace with a new line

###Goal 3: "Remove brackets" ####Find Pattern (.*)[{}]$

  • ( opends a capture group
    • . any character except new line
    • * preceeding token zero to infinite times
  • ) closes the capture group
  • [ initiates new character class
    • {} "literal { or literal }"
  • ] closes character class
  • $ end of line.
    • since we removed commas in Goal 2, all } should be followed by an end of line.

####Replace With $1

  • replace with capture group 1, or anything on the same line that came before the bracket

###Goal 4: Remove excess new lines ####Find Pattern \n *$

  • \n a new line
  • a space
  • * preceeding token zero to infinite times (space)
  • $ end of line

####Replace With

  • replace with nothing, removing the selection
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment