3

The expression

"abcb".replace(/(?:a)b/, 'x')

returns "xcb". What I want it return is "axcb"; that is, the "a" is not captured.

Is this possible in a single regex?

Michael Lorton
  • 43,060
  • 26
  • 103
  • 144
  • 1
    I'm not sure I get your intention but how about `"abcd".replace(/ab/, 'ax')`? – collapsar Mar 11 '15 at 20:52
  • Seriously - That is the whole point of a **non**-capturing group. This question is weird (sorry if my comment isn't constructive). Can you change the pattern? – Kobi Mar 11 '15 at 20:54
  • Related: http://stackoverflow.com/questions/7376238/javascript-regex-look-behind-alternative – radiaph Mar 11 '15 at 21:02
  • ["non-capturing" is with regard to remembering the match for subexpressions](https://www.youtube.com/watch?v=G2y8Sx4B2Sk) – zzzzBov Mar 11 '15 at 21:06
  • The question should be clarified in regards of what shall be achieved. You desired result can also be obtained via '"abcd".replace(/b/, 'x')' – SGD Mar 11 '15 at 21:10
  • @SGD -- I want to replace "b" if and only if it is preceded by an "a". – Michael Lorton Mar 11 '15 at 22:49
  • @collapsar -- in the actual problem, the RE I want to not capture is more complicate than "a". anubhava's suggestion would work. – Michael Lorton Mar 11 '15 at 22:52

1 Answers1

1

You can make it capturing:

"abcd".replace(/(a)b/, '$1x')
//=> axcd
anubhava
  • 761,203
  • 64
  • 569
  • 643