2

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?
4

3 回答 3

3

当然,只需放在gender组内style

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)

于 2019-04-27T12:20:23.887 回答
1

我建议只为后面的前两个和四个字符设置单独的捕获组。然后,style通过将前两个捕获组连接在一起来形成:

var input = "1102961D048.075";
var regex = /(.{2})(.{4})(.{2})(.{3}).(.{3})/g;
var match = regex.exec(input);
console.log("gender_code: " + match[1]);
console.log("style: " + match[1] + match[2]);

作为风格说明,我不喜欢使用命名捕获组,因为它们往往会导致正则表达式臃肿且难以阅读。

于 2019-04-27T12:18:20.213 回答
1

是的,您可以使用此正则表达式使用积极的前瞻性来捕获性别代码,

(?=(..))(\d{6})(\d{1}[ABDE])(\d{3})\.(\d{3})

正则表达式演示

这被命名为组正则表达式,但仅适用于 Chrome 浏览器

命名捕获分组将在 ECMAScript 2018 中可用,目前仅在 Chrome 中受支持。

这个 JS 演示将在 Chrome 中运行,因为它是目前唯一支持 EcmaScript2018 的演示,

const validateMpn = (mpn) => {
  const regex = /(?=(?<gender_code>\d\d))(?<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)

于 2019-04-27T12:21:01.383 回答