Reputation: 181
I am using JavaScript
and would like to match everything in a custom template language like this:
Begin10
Match THIS keyword and ANOTHER
End10
So I would like to find Begin10
using the 10 as variable to find End10
and match THIS and ANOTHER between them.
I've looked at capture groups. I assume this is the way to go, but I can't figure out how to compose the expression.
THIS
and ANOTHER
need to be targeted for syntax highlighting by my code.
Upvotes: 0
Views: 196
Reputation: 115282
You can use regex with captured group
var str = `Begin10
Match THIS keyword and ANOTHER1
End10
Begin20
Match THIS keyword and ANOTHER2
End20`;
console.log(
str.match(/\bBegin(\d+)[\s\S]*?\bEnd\1\b/g)
);
var str = `Begin10
Match THIS keyword and ANOTHER1
End10
Begin20
Match THIS keyword and ANOTHER2
End20`;
var res = [],
regex = /\bBegin(\d+)\s+([\s\S]*?)\s+\bEnd\1\b/g,
match;
while (match = regex.exec(str)) {
res.push(match[2]);
}
console.log(res);
UPDATE :
If there is only THIS
or ANOTHER
between them then use
var str = `Begin10
THIS
End10
Begin20
ANOTHER
End20`;
var res = [],
regex = /\bBegin(\d+)\s+(THIS|ANOTHER)\s+\bEnd\1\b/g,
match;
while (match = regex.exec(str)) {
res.push(match[2]);
}
console.log(res);
Upvotes: 2
Reputation: 19206
\nBegin(\d+)\s*\nMatch \b(\w+)\b keyword and \b(\w+)\b\s*\nEnd\1\n
\n
will match a newline, and I am sure you don't want to get anything besides newline.\1
that's a variable for the first group to make sure it has the same value.\s*
just to ignore some unnecessary whitespaces.Upvotes: 0