Skip to main content
Legend
March 22, 2024
Answered

Regex to remove pattern from sequence

  • March 22, 2024
  • 2 replies
  • 1203 views

Hi,

 

I have a sequence of strings seperated by a comma.

 

1x,2x,1y,2y,1aa,2aa,1bb,1cc,2bb,2cc

 

I want to remove all of the strings starting with 2.  So my string would look like this:

1x,1y,1aa,1bb,1cc

 

I want to maintain the comma delimiter. Note the end of the sequence does not have a comma.

Currently I am using:

 

var s = "1j,2j,1vv,2vv,2xx,1N,2Y,1abc";

s = ( s.replace ( "2[^,]*", "", "g"));

alert ( s );

 

But I get left with double comma, which I clean up later.

 

Any suggestions for a better, faster solution, would be very welocome.

 

Thanks.

 

P.

 

This topic has been closed for replies.
Correct answer m1b

Hi @Pickory, not a huge improvement but this is how I would do it:

var s = '2x,1y,2y,1aa,2aa,1bb,1cc,2bb,2cc'
    .replace(/(^|,)2[^,]*/g, '')
    .replace(/^,/, '');

$.writeln(s);

 The 2nd replace is needed for when the "2" is found at the start.

- Mark

2 replies

Community Expert
March 23, 2024

I just tried a GREP search didn't do the script 

 

but this works for me in GREP

,(?<=,)2\w+

 

Change all seems to work

 

 

 

m1b
Community Expert
Community Expert
March 23, 2024

Hi @Eugene Tyson, yes that's how you would do it via the UI, but you can't use lookbehinds in ExtendScript RegExp.

- Mark

Community Expert
March 23, 2024

Ah yes - I see that - just wanted to put the GREP up there in case it was useful 😄

Thanks

m1b
Community Expert
m1bCommunity ExpertCorrect answer
Community Expert
March 23, 2024

Hi @Pickory, not a huge improvement but this is how I would do it:

var s = '2x,1y,2y,1aa,2aa,1bb,1cc,2bb,2cc'
    .replace(/(^|,)2[^,]*/g, '')
    .replace(/^,/, '');

$.writeln(s);

 The 2nd replace is needed for when the "2" is found at the start.

- Mark

PickoryAuthor
Legend
March 23, 2024

Thank you all for looking.

 

I think I will go with the one from Mark.

 

P.

Marc Autret
Legend
March 25, 2024

Hi Pickory,

 

Definitely just for fun:

s = ((','+s).match(/,[^2][^,]*/g)||[]).join('').slice(1);

😉

 

Best,

Marc