How would I remove just the whole number from this output?

Hello,

I’m very new to scripting with AppleScript and have searched many forums but can’t seem to nail this seemingly simple issue. I would like to extract ONLY the whole number which is subject to change from the sample output below. It is contained in the clipboard and once extracted I would like to replace the clipboard with only the extracted whole number. Any help would be greatly be appreciated…

• Before
Commission Amount
$40.00

•After
40

This is a job for AppleScript’s text item delimiters, a.k.a. TIDs.
There’s a tutorial here.
Warning: this will fail when the dollar sign and/or the dot is missing.

-- read the clipboard
set x to (get the clipboard)

-- store current value of TIDs, and set our own  
set {TIDs, AppleScript's text item delimiters} to {AppleScript's text item delimiters, {"$", "."}}

set x to text items of x --> a list of 3 items…
set x to item 2 of x -- …of which we want the 2nd

-- restore old value of TIDs
set AppleScript's text item delimiters to TIDs

-- put the number into the clipboard
set the clipboard to x

#	short version:
set x to (get the clipboard)
set {TIDs, AppleScript's text item delimiters} to {AppleScript's text item delimiters, {"$", "."}}
set x to text item 2 of x -- NotaBene: we're now getting a 'text item', not an 'item'
set AppleScript's text item delimiters to TIDs
set the clipboard to x

This is an alternative solution using Regular Expression and AppleAScriptObjC.

The weird NSNotFound property avoids an bridging inconsistency documented at Late Night Software

use AppleScript version "2.4" -- Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

property NSNotFound : a reference to 9.22337203685477E+18 + 5807

set theText to (get the clipboard)
set cocoaString to current application's NSString's stringWithString:theText
set theRange to cocoaString's rangeOfString:"\\d+" options:(current application's NSRegularExpressionSearch)
if theRange's location is NSNotFound then return
set subString to cocoaString's substringWithRange:theRange
set the clipboard to subString as text

If you want to extract the whole number including decimal places use the pattern “[0-9.]+”

I like alastor933’s solution, which is simple and clean, but FWIW a third approach is as shown below. This breaks easily, although error checking can improve this.


set clipboardOld to paragraph 2 of (the clipboard)

set clipboardNew to {}

repeat with i from 1 to (count clipboardOld)
	set aCharacter to item i of clipboardOld
	if aCharacter is in {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0"} then
		set the end of clipboardNew to aCharacter
	else if aCharacter is equal to "." then
		exit repeat
	end if
end repeat

set the clipboard to clipboardNew as text

Also check out math tutorial here https://macscripter.net/viewtopic.php?id=24724

If you remove the $ from your text then read it as a real or integer
(Read the tutorial for more info)