I have a script which calculate the timeframe between date and return the result in days or month or years.
For exemple, given myResult = "6 Days"
How can I separate the number from the text ?
I managed to get the number only using this :
set myResultNumberOnly to number of myResult
but I can't manage to do the same from the text :
set myResultTextOnly to text of myResult
I also tried
set myResultTextOnly to word of myResult
Maybe I can go with text delimiting?
I can't tell the length of the number using this :
set theLength to (get length of (myResultTextNumberOnly as text))
Or should I go with if statement?
How would be the best way to do it?
UPDATE
I just realised that set myResultNumberOnly to number of MyResult give a wrong number, I don't really understand why ?
set MyResult to "Account Value:$478.01"
set myResultNumberOnly to number of MyResult
Result: 21
Best Answer
number of MyResult
obtains the length of a string."6 days"
just happens to be 6 characters long, whereas"Account Value:$478.01"
is 21 characters long.The most straightforward method to extract numbers from a string would be to split the string into words, then test each item of the list individually to see whether it can be coerced into a number:
This won't handle string representations of numbers in scientific notation, e.g.
1.234E+09
, as the method AppleScript uses to delimit its words results in{"1.234E", "+", "09"}
. In this case, you can settext item delimiters
tospace
, and perform the same operation on thetext items of My Result
.I do question, however, why your script is producing a result that is a string value of "6 days". It makes me believe the script you are using to calculate time intervals between dates is not doing it in as an amenable way as it could. Partly, this depends on the input your script receives, but in many cases, you should consider converting the input into AppleScript date objects, which then allows you to calculate differences easily and returns to you an actual number that you can manipulate to acquire a measure in days, minutes, hours, etc.
The example script below assumes an ISO 8601-formatted date string as input, i.e.
"yyyy-mm-dd"
, although you could adapt the script to cater for other input formats: