【发布时间】:2019-04-27 12:13:13
【问题描述】:
我正在使用命名捕获组来验证和提取产品编号中的数据。产品编号的格式如下:
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
我当前的代码如下所示:
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)
由于gender_code 和style 重叠,我不确定如何同时获得它们。因此我有以下问题:
- 是否可以只使用一个正则表达式?
- 如果是,我该如何做到这一点?
【问题讨论】:
标签: javascript regex validation named-captures