1

This is going to be a really short question...

Lets assume I have a regex like:

(Hello)(?:fooBar)

How can I backreference it using \2? I know this works with normal capturing groups and that a non capturing group only groups tokens together but if there is any work-around then I would be glad to know.

Edit: Problem is:

I need to backreference to non capturing groups sometimes. For example there are moments where I really dont want that group to show up as a match but it shows up multiple times in the pattern which is why I prefer to backreference it.

8
  • Try adding a second empty capturing group - (Hello)(?:fooBar)(). Or an outer group: ((Hello)(?:fooBar)). Or ((Hello))(?:fooBar), (Hello)((?:fooBar)), etc. What are you trying to achieve? Commented Jan 23, 2017 at 8:21
  • @WiktorStribiżew didnt know this question was bad quality. Isnt it clear what im asking? Commented Jan 23, 2017 at 8:23
  • What are you asking for? What is the real problem? Please clarify. Commented Jan 23, 2017 at 8:25
  • 2
    That is not possible to backreference a non-capturing group as it does not create any memory buffers with the captured texts. Commented Jan 23, 2017 at 8:29
  • @WiktorStribiżew ya, I thought so, that is really unfortunate but oh well. At least my doubts are gone now xD. Commented Jan 23, 2017 at 8:30

1 Answer 1

2

As mentioned in the comments, a backreference applies only to a capture group.

But it sounds like your actual concern is with not repeating yourself. In this case, you can construct the regex:

const f = 'foobar';
const r = new RegExp(`Hello${f}blah${f}blah${f}blah`);
Sign up to request clarification or add additional context in comments.

1 Comment

Actually you are right. It should have crossed my mind. I hardly used the regex object.

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.