blip009
blip009

Reputation: 35

regex experession to extract complete address starting from house number if unit numbers are present

I'm trying to extract address starting from house numbers if unit numbers are present in given string.

If unit numbers are not available, select whole string.

const adss1 = 'U 4 21 House Ave, Suburb State 2020';

const adss2 = 'U 14 21 House Ave, Suburb State 2020';

const adss3 = '21 House Ave, Suburb State 2020';

const regEx = /(([0-9]+)((\s+[a-zA-Z,]+|\s+[a-zA-Z,.]+\s){2,10})?(\#[0-9a-z-\-]+|\#\s+[0-9\-]+|[0-9\-]+))/g;

const match1 = adss1.match(regEx)
console.log(match1)
// [ '21 House Ave, Suburb State 2020' ]
const match2 = adss2.match(regEx)
console.log(match2)
//[ '14', '21 House Ave, Suburb State 2020' ]
const match3 = adss3.match(regEx)
console.log(match3)
//[ '21 House Ave, Suburb State 2020' ]

Current regex pattern works for adss1 and adss3 address type but not for adss2 variable.

Looking for recommendations to improve my regex pattern. Thanks

Upvotes: 2

Views: 196

Answers (1)

Peter Seliger
Peter Seliger

Reputation: 13417

From what I see, one just wants to skip everything in the beginning until one matches the first digit character(s) before a whitespace (sequence) followed by a non digit character; and from there one just continues matching everything (until the end) ... /\d+\s+\D.*$/ ...

function extractAddress(data) {
  return ((/\d+\s+\D.*/).exec(String(data)) || [''])[0];
}
console.log([

  'U 4 21 House Ave, Suburb State 2020',
  'U 14 21 House Ave, Suburb State 2020',
  '21 House Ave, Suburb State 2020',

  'hasvk 1223 21 House Ave, Suburb State 2020',
  'has vk 12 23 21 House Ave, Suburb State 2020',
  '12 23 21 House Ave, Suburb State 2020',

].map(extractAddress));

console.log(`U 4 21 House Ave, Suburb State 2020
U 14 21 House Ave, Suburb State 2020
21 House Ave, Suburb State 2020
hasvk 1223 21 House Ave, Suburb State 2020
has vk 12 23 21 House Ave, Suburb State 2020
12 23 21 House Ave, Suburb State 2020`.match(/\d+\s+\D.*$/gm));
.as-console-wrapper { min-height: 100%!important; top: 0; }

Upvotes: 1

Related Questions