• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
How best to extract digits from a string?
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

How best to extract digits from a string?


  • Subject: How best to extract digits from a string?
  • From: Bill Cheeseman <email@hidden>
  • Date: Wed, 25 Apr 2001 17:04:47 -0400

All these years I have been testing whether a character is a numerical digit
by trying to coerce it to an integer and handling the error if it can't be
coerced. Come to find out, the characters "+", "-", etc. -- most of the
single-character arithmetic operators -- return the integer value 0 (zero)
when coerced to integer, without generating the error I always expected. At
first, this seemed like a bug, since I didn't ask to run the string as a
script.

But I see now that it might more properly considered a feature, since
coercion isn't meant to be used as a filter but rather to make a script work
if any sensible way can be found to do so. "+" could reasonably be
interpreted as the statement (0 + 0) in these circumstances, although an
arithmetic operator standing by itself won't compile as a script. (Yes,
converting either of the two single-character division operator characters
to integer generates an error, although it is the 'can't coerce' error, not
a 'divide by 0' error.)

So now I filter for numerical digits as in this example:

set digits to "1234567890"
set input to "(800) 555-1212"
set output to "" -- initialize
repeat with char in every character of input
if char is in digits then set output to output & char
end repeat
get output --> "8005551212"

Is there a more efficient way to do this?

--

Bill Cheeseman - email@hidden
Quechee Software, Quechee, Vermont, USA

The AppleScript Sourcebook - www.AppleScriptSourcebook.com
Vermont Recipes - www.stepwise.com/Articles/VermontRecipes


  • Follow-Ups:
    • Re: How best to extract digits from a string?
      • From: Harald E Brandt <email@hidden>
    • Re: How best to extract digits from a string?
      • From: Paul Berkowitz <email@hidden>
  • Prev by Date: [OT] Better list response [WAS: Re: error -48 duplicate name postscripting from xpress 4.1]
  • Next by Date: off the subject...
  • Previous by thread: [OT] Better list response [WAS: Re: error -48 duplicate name postscripting from xpress 4.1]
  • Next by thread: Re: How best to extract digits from a string?
  • Index(es):
    • Date
    • Thread