AppleScript: how to extract numbers from a string
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 inputString
do shell script "sed s/[a-zA-Z\\']//g <<< " & s
set dx to the result
set numlist to {}
repeat with i from 1 to count of words in dx
set this_item to word i of dx
try
set this_item to this_item as number
set the end of numlist to this_item
end try
end repeat
return numlist
end 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:
set theNums 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.
If you want to see this handler in action, take a look at my battery health meter script. 🙂
Posted on August 6, 2014, in AppleScript and tagged Excel, InDesign, numbers, pages, Quark, string, Word. Bookmark the permalink. Comments Off on AppleScript: how to extract numbers from a string.