Reputation: 1725
Problem:
--
Input: "ABC-PQR--1-XYZ"
Expected Output: ['ABC', 'PQR', '-1', 'XYZ']
--
Input: "ABC-PQR-7-15-XYZ"
Expected Output: ['ABC', 'PQR', '7-15', 'XYZ']
--
I tried using lookback and lookahead regex. Getting confused. Any pointers?
.split(/(?<=\d)-/);
https://jsfiddle.net/ye5ojhcs/4/
Upvotes: 1
Views: 423
Reputation: 6043
Try this:
/-(?=[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);
Upvotes: 1
Reputation: 2549
Also this is the simple approach with simple logic:
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);
Upvotes: 1
Reputation: 386560
You could match the wanted parts by looking for
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; }
Upvotes: 2