How do I capture all 1, 2 and 3 in not |1|2|3|
My regex \|(.*?)\|
skips 2.
const re = /\|(.*?)\|/gi;
const text = 'not |1|2|3|'
console.log(text.match(re).map(m => m[1]));
CodePudding user response:
You can use
const re = /\|([^|]*)(?=\|)/g;
const text = 'not |123|2456|37890|'
console.log(Array.from(text.matchAll(re), m => m[1]));
Details:
\|
- a|
char([^|]*)
- Group 1: zero or more chars other than|
(?=\|)
- a positive lookahead that matches a location that is immediately followed with|
.
If you do not care about matching the |
on the right, you can remove the lookahead.
If you also need to match till the end of string when the trailing |
is missing, you can use /\|([^|]*)(?=\||$)/g
.