Arcaeca
Arcaeca

Reputation: 271

Can you forward-reference a named capture group in JS regex?

So the thing I'm trying to do with regex (JS flavor) is essentially to match words with double letters (i.e. two instances of the same character, directly adjacent to each other), but only capture the second letter. So for example, I would want to capture the second t in letter, the second n in manner, and the second s in glass.

The way I thought to go about this with a backreference to a named capture group, which I called ditto. So in this case the regex would be /(?:\k<ditto>)(?<ditto>t|n|s)/g...

...but this ended up matching strings it shouldn't have, namely strings with only a single t, n or s - i.e., it's matching the exact the same thing as /[tns]/g - and I just figured out it's because \k can't backreference a <ditto> match that hasn't been found yet, so the first capture group might as well just be empty.

So what I actually need is a forward-reference, not a backreference, but those... don't exist, do they? Then how else would you accomplish the same thing?

Upvotes: 0

Views: 171

Answers (1)

Barmar
Barmar

Reputation: 780724

Use capture groups around both occurrences. Then you can copy one to the replacement to keep it, while replacing the other.

string.replace(/([tns])(\1)/g, "X$2"); // replace first with X
string.replace(/([tns])(\1)/g, "$1X"); // replace second with X

Upvotes: 1

Related Questions