Prepare For Output--Fix Phone
The following script contains a method that you may instead wish to call from within your "Write to CSV" script. The purpose of the script is to put phone numbers into a standard format (123-456-7890 x 1234) prior to output. Note: Be careful when using this script to work with non-U.S. phone numbers, since other countries may have more or fewer digits.
String fixPhone(String phone){
if (phone!=null && phone!=void){
session.log("+++Dealing with phone formated: " + phone);
// Replace non-digits with nothing
// Note: "\\D" is a regular expression that means "not a digit"
phone = phone.replaceAll("\\D", "");
// If there is a leading 1, remove it
if (phone.startsWith("1")){
session.log("+++Starts with a one, so removing.");
phone = phone.substring(1,phone.length());
}
// Reformat the phone to the format: "123-456-7890"
if (phone.length()>=10){
area = phone.substring(0,3);
prefix = phone.substring(3,6);
number = phone.substring(6,10);
newPhone = "(" + area + ") " + prefix + "-" + number;
}
else{
session.log("---Error: phone number hasn't enough digits");
}
// Deal with phone extensions
if (phone.length()>10){
newPhone += " x";
newPhone += phone.substring(10,phone.length());
}
}
return "\"" + ((newPhone==null || newPhone==void)? "" : newPhone ) + "\"";
}
if (phone!=null && phone!=void){
session.log("+++Dealing with phone formated: " + phone);
// Replace non-digits with nothing
// Note: "\\D" is a regular expression that means "not a digit"
phone = phone.replaceAll("\\D", "");
// If there is a leading 1, remove it
if (phone.startsWith("1")){
session.log("+++Starts with a one, so removing.");
phone = phone.substring(1,phone.length());
}
// Reformat the phone to the format: "123-456-7890"
if (phone.length()>=10){
area = phone.substring(0,3);
prefix = phone.substring(3,6);
number = phone.substring(6,10);
newPhone = "(" + area + ") " + prefix + "-" + number;
}
else{
session.log("---Error: phone number hasn't enough digits");
}
// Deal with phone extensions
if (phone.length()>10){
newPhone += " x";
newPhone += phone.substring(10,phone.length());
}
}
return "\"" + ((newPhone==null || newPhone==void)? "" : newPhone ) + "\"";
}
scraper on 07/16/2010 at 4:24 pm
- Printer-friendly version
- Login or register to post comments