in Appcelerator Titanium

I recently needed to clean up a data file in an Appcelerator Titanium project I was working on by removing the double quotes surrounding some numbers.

Stuff like: “20”
Needed to be: 20

It is pretty easy to match this with a regular expression, and Titanium Studio’s (and Eclipse’s) Find and Replace functionality has Regular Expression integration, which is perfect for a job like this.

Since we are replacing the matched text with the number found inside the quotes, the key is getting that number to be the value in the ‘Replace’ side of the find and replace.  Again, pretty easy using regex, as we can just use parentheses to capture the digits, then reference the capture in the ‘Replace’ section.

Below is a screenshot. To see this in Studio, open up an editor and do a Ctrl/Cmd + F, or Edit > Find/Replace.

titanium-studio-regex-find-replace

Here’s a breakdown of the regex:

  • d is a shortcut, or predified term meaning ‘any decimal digit’
  • The + sign says to match one or more of whatever is before me, or ‘one or more digit’.  This is how we can match 4, 25, 112, etc.
  • The double quotes at the beginning and end are just that, the double quotes that need to be found surrounding our one or more digits.
  • The parentheses surround the capture group, which will be one or more digits.

The capture group () makes this all nice and easy. Anything inside the parentheses (one or more digits) will be put in the replace box, as referenced with $1.  $1 references the first capture group.  If we had a second capture, $2 would match it, and so on.

I’m still a complete beginner at regex (which is probably why I was so impressed with myself at this simple task that I created a blog post about it), and of all the how-to sites and explantations out there, I have found the best regular expressions tutorial to be in John Resig’s and Bear Bieault’s Secrets of the JavaScript Ninja.

Also, If you see an issue with my regex, let me know!