2

Given the string: the_number_10_is_important, I want to capture _10_ and exclude 10.

I essentially want to replace all underscores surrounding digits with brackets.

_\d+_ selects _10_ is my starting point. I'm trying to use lookaround or a non-capturing group eg. _(?:\d+)_

Logan C
  • 41
  • 3

2 Answers2

0

Just to close this then, with credit to The fourth bird

You have to use a capture group and repeat the digits "the_number_10_is_important".replace(/_(\d+)_/g, "[$1]");

Here's my own version, but with sed which doesn't have proper support for \d:

sh$ echo "the_number_10_is_important_ but 10 should not be fooled by the real_0_ or the fake_1" | sed -E -e 's/_([0-9]+)_/[\1]/g'
the_number[10]is_important_ but 10 should not be fooled by the real[0] or the fake_1
0

You need to capture the number and give it back in the replacement, so you replace the whole _10_ part instead of just the underscores.

var s = "the_number_10_is_important";
var x = s.replace(/_(\d+)_/gm, "($1)");
console.log(x);

It is possible to do it your way too with lookaround, but it is somewhat more complicated.

var s = "the_number_10_is_important";
var x = s.replace(/_(?=\d+)/gm, "(").replace(/(?<=\d+)_/gm, ")");
console.log(x);
inf3rno
  • 24,976
  • 11
  • 115
  • 197