Clovertech
› Clovertech Forums › Read Only Archives › Cloverleaf › Cloverleaf › format phone number
If I have a phone number 1234567890 and want to the format to be (123)456-7890, how do I do that in Tcl? I’m thinking maybe string format or regexp, but thought I ask you guru first 😛
I would first like to do a check to see if the format is correct and then if is not to change the format. I believe regexp could do that. Ideas?
This does not look efficient for changing the format, but I did this:
%set phone 1234567890
% set areacode [ string range $phone 0 2 ]
123
% set num1 [ string range $phone 3 5 ]
456
% set num2 [ string range $phone 6 end ]
7890
% set final_num ($areacode)$num1-$num2
(123)456-7890
If an unformatted number it would be all numbers and 10 digits long otherwise it is either formatted or a bogus number
set phone 1234567890
if {[string is digit -strict $phone] && [string length $phone] == 10} {
regsub — {(d{3})(d{3})(d{4})} $phone {(1)2-3} phone
}
echo $phone
=> (123)456-7890
Thanks Charlie, that’s some nifty regsub 😛