小编Uni*_*nic的帖子

JavaScript正则表达式中的多个嵌套匹配项

尝试编写正则表达式以匹配GS1条形码模式(https://en.wikipedia.org/wiki/GS1-128),其中包含2个或更多这些模式,这些模式具有标识符,后跟一定数量的数据字符.

我需要此条形码匹配的东西,因为它包含2个标识符和数据模式:

人类可读与parens中的标识符:(01)12345678901234(17)501200

实际数据: 011234567890123417501200

但是当只有一个模式时,不应匹配此条形码:

人类可读:(01)12345678901234

实际数据: 0112345678901234

似乎以下应该有效:

var regex = /(?:01(\d{14})|10([^\x1D]{6,20})|11(\d{6})|17(\d{6})){2,}/g;
var str = "011234567890123417501200";

console.log(str.replace(regex, "$4"));
// matches 501200
console.log(str.replace(regex, "$1"));
// no match? why?
Run Code Online (Sandbox Code Playgroud)

由于一些奇怪的原因,一旦我删除{2,}它的工作,但我需要它,{2,}以便它只返回匹配,如果有多个匹配.

// Remove {2,} and it will return the first match
var regex = /(?:01(\d{14})|10([^\x1D]{6,20})|11(\d{6})|17(\d{6}))/g;
var str = "011234567890123417501200";

console.log(str.replace(regex, "$4"));
// matches 501200
console.log(str.replace(regex, "$1"));
// matches 12345678901234
// but then the problem is it would also match …
Run Code Online (Sandbox Code Playgroud)

javascript regex

6
推荐指数
1
解决办法
1280
查看次数

标签 统计

javascript ×1

regex ×1