Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extract phone number with spaces from text

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
"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading