尝试编写正则表达式以匹配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 single identifiers such as
var str2 = "0112345678901234";
console.log(str2.replace(regex, "$1"));
Run Code Online (Sandbox Code Playgroud)
我如何使这项工作如果只有一组匹配组,它将只匹配和拉取数据?
谢谢!
对于 Perl 兼容正则表达式 (PCRE),您的 RegEx 在逻辑和语法上都是正确的。我相信您面临的问题是 JavaScript 存在重复捕获组的问题。这就是为什么一旦你取出 .RegEx 就可以正常工作的原因{2,}。通过添加量词,JavaScript 将确保只返回最后一个匹配项。
我建议删除{2,}量词,然后以编程方式检查匹配项。我知道这对于那些 RegEx 的忠实粉丝来说并不理想,但这就是生活。
请参阅下面的片段:
var regex = /(?:01(\d{14})|10([^\x1D]{6,20})|11(\d{6})|17(\d{6}))/g;
var str = "011234567890123417501200";
// Check to see if we have at least 2 matches.
var m = str.match(regex);
console.log("Matches list: " + JSON.stringify(m));
if (m.length < 2) {
console.log("We only received " + m.length + " matches.");
} else {
console.log("We received " + m.length + " matches.");
console.log("We have achieved the minimum!");
}
// If we exec the regex, what would we get?
console.log("** Method 1 **");
var n;
while (n = regex.exec(str)) {
console.log(JSON.stringify(n));
}
// That's not going to work. Let's try using a second regex.
console.log("** Method 2 **");
var regex2 = /^(\d{2})(\d{6,})$/;
var arr = [];
var obj = {};
for (var i = 0, len = m.length; i < len; i++) {
arr = m[i].match(regex2);
obj[arr[1]] = arr[2];
}
console.log(JSON.stringify(obj));
// EOFRun Code Online (Sandbox Code Playgroud)
我希望这有帮助。