Home > Mobile >  Extract phone number with spaces from text
Extract phone number with spaces from text

Time:04-05

I have the below text in a cell F2 (got from getplainbody from email)

"Preston 082 534 2133 Alberton Gauteng Furniture removal 1ton

Phone 45 "

I want to extract only the phone number 0825342133 in G2

The below code is extracting only if the number is a 10 digit number (without space in between).

function get_phone() {//
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Emails"); //
  var dvals=sheet.getRange("F:G").getValues();//
  var tel=[];
  for (i=1; i<dvals.length; i  ){
    if (dvals[i][1]==""){
        tel=dvals[i][0].match(/[\ ]?\d{10}|\(\d{3}\)\s?-\d{6}/)  ;
        if (tel){sheet.getRange("G" (i 1)).setValue(tel[0])};
    }
  }
}
//

How to extract if it is a 10 digit number with two space in between?

CodePudding user response:

Changing the regular expression like this will match also ### ### ####:

tel = body.match(/[\ ]?\d{10}|\(\d{3}\)\s?-\d{6}|\d{3}\s\d{3}\s\d{4}/);

But it's not a very solid way to parse that telephone number. I'm quite sure you would be better server with something like:

[\d\s] 

Because it would match every combination of spaces and digits but yet you would need to validate the results after the match to be sure nothing else numeric was matched.

  • Related