Blog Archives

Here’s a little handler I wrote in response to a query over on ASC, that will return all the numbers in a string of text. This could be really handy for all sorts of tasks, like extracting data from a text document in order to import the data into a spreadsheet or indexing page numbers from InDesign or Quark, for instance.

Here’s the handler:

on returnNumbersInString(inputString)set s to quoted form of inputStringdo shell script "sed s/[a-zA-Z\\']//g <<< " & sset dx to the resultset numlist to {}
repeat with i from 1 to count ofwordsindxset this_item to word i of dxtryset this_item to this_item as numberset the end of numlist to this_itemend tryend repeatreturn numlistend returnNumbersInString

To use it , place the handler somewhere in your script (handlers usually go at the beginning or end of your script, but it’s up you; AppleScript doesn’t care where you put them!). Then call it like so:

settheNums to returnNumbersInString(“put your string with some numbers like $45.12, 20%, 12 months, and other assorted data here, or use a variable that points to your text “)

The handler does the work, and sets theNums to a list containing all the numbers in your text. In the example, you’ll see the result as {45.12, 20, 12}.

After that, you’re free to sort them or send them to another app or do whatever your script wants to do with numbers.