Re: How best to extract digits from a string?
Re: How best to extract digits from a string?
- Subject: Re: How best to extract digits from a string?
- From: "Arthur J Knapp" <email@hidden>
- Date: Fri, 27 Apr 2001 13:46:38 -0400
>
Date: Wed, 25 Apr 2001 17:04:47 -0400
>
Subject: How best to extract digits from a string?
>
From: Bill Cheeseman <email@hidden>
I'm a bit backed up in my correspondence...
>
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?
For larger strings, you may find some speed advantages with
this larger code snippet:
set digits to "1234567890"
set input to "(800) 555-1212"
set output to s_contiguous(input, digits)
-- > { "(", "800", ") ", "555", "-", "1212", "" }
-- "Numbers" are the even items
repeat with x from 1 to length of output by 2
set item x of output to 0
end repeat
set output to "" & every string of output
-- > "8005551212"
on s_contiguous(str, sub)
-- str = "(800) 555-1212"
set oldDelim to text item delimiters
try
set sentinal to ASCII character 1
-- > let's pretend: "^"
repeat with i in sub
set text item delimiters to {"" & i}
set str to text items of str
-- > First loop: { "(800) 555-", "2", "2" }
-- > Second loop: { "(800) 555-^1^", "^1^", "" }
set text item delimiters to {sentinal & i & sentinal}
set str to "" & str
-- > First loop: "(800) 555-^1^2^1^2"
-- > Second loop: "(800) 555-^1^^2^^1^^2^"
end repeat
-- str = "(^8^^0^^0^) ^5^^5^^5^-^1^^2^^1^^2^"
set text item delimiters to {sentinal & sentinal}
set str to text items of str
-- > { "(^8", "0", "0^) ^5", "5", "5^-^1", "2", "1", "2^" }
set text item delimiters to {""}
set str to "" & str
-- > "(^800^) ^555^-^1212^"
set text item delimiters to {sentinal}
set str to text items of str
-- > { "(", "800", ") ", "555", "-", "1212", "" }
on error m number n
set text item delimiters to oldDelim
error m number n
end try
set text item delimiters to oldDelim
return str
end s_contiguous
Arthur J. Knapp
http://www.stellarvisions.com
mailto:email@hidden
Hey, check out:
http://MacScripter.net