javascriptregexvalidationnamed-captures

Overlapping named capturing groups


I'm using named capturing groups to validate and extract data out of a product number. The format of the product number looks like this:

1102961D048.075

Chars 1-2     gender_code   11
Chars 1-6     style         110296
Chars 7-8     width_code    1D
Chars 9-11    color_code    048
Char  12      delimiter     ignored
Chars 13-15   size_code     075

My current code looks like this:

const validateMpn = (mpn) => {
  const regex = /(?<style>\d{6})(?<width>\d{1}[ABDE])(?<color_code>\d{3})\.(?<size_code>\d{3})/gi
  const match = regex.exec(mpn)

  if (!match) {
    return null
  }

  return match.groups
}

const str1 = '1102961D048.075'
const str2 = '1200322A001.085'
const match1  = validateMpn(str1)
const match2  = validateMpn(str2)

console.log(match1)
console.log(match2)

As gender_code and style overlap I'm not sure how to get them both. Therefore I have the following questions:

  1. Is it possible to this with only one regular expression?
  2. If yes, how could I accomplish this?

Solution

  • Sure, just place gender inside the style group:

    const validateMpn = (mpn) => {
      const regex = /(?<style>(?<gender>\d{2})\d{4})(?<width>\d{1}[ABDE])(?<color_code>\d{3})\.(?<size_code>\d{3})/gi
      const match = regex.exec(mpn)
    
      if (!match) {
        return null
      }
    
      return match.groups
    }
    
    const str1 = '1102961D048.075'
    const str2 = '1200322A001.085'
    const match1  = validateMpn(str1)
    const match2  = validateMpn(str2)
    
    console.log(match1)
    console.log(match2)