I want to repetedly capture a certain pattern. My pattern is #|X|#YYY
, where X
is any single letter, and YYY
is any string, and the #
and |
characters are hardcoded separator characters.
For example, this is my Input String: #|m|#this is string #1#|m|#this is string #2#|m|#this is string #3
This is my desired output:
Match:
- Group 1: m
- Group 2: this is string #1
Match:
- Group 1: m
- Group 2: this is string #2
Match:
- Group 1: m
- Group 2: this is string #3
I tried this:
const pattern = /#|(w+)|#(.*)/g;
const input = "#|m|#this is string #1#|m|#this is string #2#|m|#this is string #3";
let match;
while ((match = pattern.exec(input)) !== null) {
const group1 = match[1];
const group2 = match[2];
console.log("Match:");
console.log("- Group 1:", group1);
console.log("- Group 2:", group2);
}
but it seems to capture too gredily and only outputs one match:
Match:
- Group 1: m
- Group 2: this is string #1#|m|#this is string #2#|m|#this is string #3
When I try to make the pattern ungreedy, I get 3 matches as desired, but group 2 is empty for some reason.
Ungreedy attempt: (notice the ?
)
const pattern = /#|(w+)|#(.*?)/g;
Output:
Match:
- Group 1: m
- Group 2:
Match:
- Group 1: m
- Group 2:
Match:
- Group 1: m
- Group 2:
What am I doing wrong? How can I make it match the whole string until the next occurence to get my desired output?