[REBOL] Re: Fast way to remove all non-numerical chars from a string
From: gregg::pointillistic::com at: 24-Sep-2007 13:07
Hi Kai,
KP> As you likely have guessed, I asked because I need to re-format
KP> phone numbers.
Here is some very old code I remembered I had here. Use what you can.
It was designed for interactive UI use, checking and reformatting
numbers as users entered them, hence the object support; not optimized
for speed in any way.
-- Gregg
ctx-phone-entry: context [
set 'format-phone-number func [
num [string! issue! object!] "String or object with /text value"
/def-area-code area-code [string! integer!]
/local left right mid obj res
] [
left: func [s len][copy/part s len]
right: func [s len] [copy skip tail s negate len]
mid: func [s start len][copy/part at s start len]
if object? num [obj: num num: obj/text]
res: either data: parse-phone-num num [
; discard leader if it's there.
if all [11 = length? data/num data/num/1 = #"1"] [
data/num: right data/num 10
]
rejoin [
rejoin switch/default length? data/num [
7 [ compose [
(either area-code [rejoin ["(" area-code ") "]][])
left data/num 3 "-" right data/num 4
]]
10 [[
"(" left data/num 3 ") "
mid data/num 4 3 "-" right data/num 4
]]
][[data/num]]
reduce either data/ext [[" ext" trim data/ext]] [""]
reduce either data/pin [[" pin" trim data/pin]] [""]
]
][num]
if obj [
obj/text: res
attempt [if 'face = obj/type [show obj]]
]
res
]
set 'parse-phone-num func [
num [string! issue!]
/local digit digits sep _ext_ ch nums pin ext
] [
digit: charset "0123456798"
digits: [some digit]
sep: charset "()-._"
_ext_: ["ext" opt "." | "x"]
nums: copy ""
rules: [
any [
some [sep | copy ch digit (append nums ch)]
| _ext_ copy ext digits
| "pin" copy pin digits
]
end
]
either parse trim num rules
[reduce ['num nums 'ext ext 'pin pin]]
[none]
]
set 'well-formed-phone-number? func [num /local data] [
either none? data: parse-phone-num num [false] [
any [
found? find [7 10] length? data/num
all [11 = length? data/num data/num/1 = #"1"]
]
]
]
]