Apply regex replace only within "scope"

Viewed 274

How can I apply regex only within a certain scope, like between two **'s?

I want to use JavaScript to change this

**
    _a_ _b_ _c_
    -d- -e- -f-
**
_a_

into this

**
    {a} {b} {c}
    (d) (e) (f)
**
_a_

Notice that the desired result is that _a_ is not changed outside of the "scope".

I can do this much

str
    .replace(/_(.*?)_/g, "{$1}")
    .replace(/-(.*?)-/g, "($1)")

but this will replace everywhere, even outside of the two **'s.

3 Answers

It was important to me to be able to make scoping with single regular expression. So it actually possible, thanks to lookbehind.

var str = `**
    _a_ _b_ _c_
    -d- -e- -f-
**
_a_`;


var pattern1 = /(\*\*((?<!\*\*).|\n)*?)_(.*?)_((.|\n)*?\*\*)/g;
var pattern2 = /(\*\*((?<!\*\*).|\n)*?)-(.*?)-((.|\n)*?\*\*)/g;

var result = str;

while(result.match(pattern1) != null)
{
    result = result.replace(pattern1, "$1{$3}$4");
}
while(result.match(pattern2) != null)
{
    result = result.replace(pattern2, "$1($3)$4");
}

console.log(result);

Related