问题:
--
输入:"ABC-PQR-1-XYZ";
预期输出:[ABC','PQR','-1','XYZ']
--
输入:"ABC-PQR-7-15-XYZ";
预期输出:[ABC','PQR','7-15','XYZ']
--
我尝试使用了lookback和lookahead regex。感到困惑。有指针吗?
.split(/(?<=d)-/);
https://jsfiddle.net/ye5ojhcs/4/
您可以通过查找来匹配所需的零件
- 范围
- 负数
- 不减去字符
const split = string => string.match(/d+-d+|(?<=-)-d+|[^-]+/g)
console.log(split("ABC-PQR--1-XYZ"));
console.log(split("ABC-PQR-7-15-XYZ"));
.as-console-wrapper { max-height: 100% !important; top: 0; }
试试这个:
/-(?=[A-Za-z-]|d+-d)/
const str = "ABC-PQR--1-APAC";
const str2 = "ABC-PQR-7-15-XYZ";
const pattern = /-(?=[A-Za-z-]|d+-d)/;
const splitt = str.split(pattern);
const splitt2 = str2.split(pattern);
console.log(splitt, splitt2);
这也是一种具有简单逻辑的简单方法:
let str = 'ABC-PQR-7-15-XYZ--3-HH';
// Replace digit groups and minus
str = str.replace(/(d+)-(d+)/g, '$1<minus>$2');
str = str.replace(/--/g, '-<minus>');
// Split
let arr = str.split('-');
// Replace markers back
arr = arr.map(val => val = val.replace(/<minus>/, '-'));
// Log
console.log(arr);