Ade
Ade

Reputation: 181

Regex match with variables

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

Answers (3)

Pranav C Balan
Pranav C Balan

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)
);

To get the string between them, do something like this

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);

Regex explanation here

Regular expression visualization


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

Aminah Nuraini
Aminah Nuraini

Reputation: 19206

\nBegin(\d+)\s*\nMatch \b(\w+)\b keyword and \b(\w+)\b\s*\nEnd\1\n

Explanation:

  1. \n will match a newline, and I am sure you don't want to get anything besides newline.
  2. \1 that's a variable for the first group to make sure it has the same value.
  3. \s* just to ignore some unnecessary whitespaces.

Upvotes: 0

rock321987
rock321987

Reputation: 11042

This will work

\bBegin(\d+)\b([\S\s]*)\bEnd\1\b

Regex Demo

Upvotes: 1

Related Questions