views:

59

answers:

3

Ok so if I have this pattern:

ab&bc&cd&de&ef

And I need to replace all the ampersands except for the first one with commas so it ends up looking like this:

ab&bc,cd,de,ef

Its probably very simple but for the life of me I can't get this one figured out...

A: 

Why not split the original string on &

Join piece1, piece2, ....pieceN with ,

Join piece0 with the result of above with &

codaddict
Its not up to me. Has to be regex.
Davis
A: 
[^&]{2}&([^&]{2}&)*

Can't help you with the javascript part, but maybe that'll help?

Cam
+3  A: 

It's not that easy because JavaScript doesn't do lookbehind.

Try

result = subject.replace(/(^(?:[^&]+&[^&]+)|[^&]+)&/g, "$1,");

Explanation:

( Capture the following into backreference $1:

^(?:[^&]+&[^&]+) Start-of-string, followed by two fields separated by an ampersand

| or

[^&]+ one field (a field being one or more non-ampersand characters).

) End of capturing group

& match an ampersand.

That way, the first ampersand will be skipped in the match. If you need to handle empty fields, then use

(^(?:[^&]*&[^&]*)|[^&]*)&
Tim Pietzcker
+1 Nice solution!
RC
That's what I needed. Man very much appreciated. Thanks!
Davis