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+)_

6
  • See if this post helps you stackoverflow.com/questions/1395177/… Commented Mar 4, 2021 at 19:49
  • You starting well, but I guess you want \d+ instead of \d to match multiple digits Commented Mar 4, 2021 at 19:49
  • Why not simply: .replace(/_(\d+)_/g, "($1)") ? Commented Mar 4, 2021 at 19:51
  • You have to use a capture group and repeat the digits "the_number_10_is_important".replace(/_(\d+)_/g, "[$1]"); Commented Mar 4, 2021 at 19:53
  • Thanks for the help. Replacing the brackets within replace seems to work fine in this case. Commented Mar 4, 2021 at 20:05

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.