Ethan Hannen
Ethan Hannen

Reputation: 177

Regex for Removing Everything Before Certain Comma Position

I'm trying to remove and replace everything before the 13th comma in an array like so:

{1,1,0,0,0,4,0,0,0,0,20,4099,4241,706,706,714,714,817,824,824,824,2,2,2,2,1,1,1,1},

to where it becomes:

{706,706,714,714,817,824,824,824,2,2,2,2,1,1,1,1},

Reference: I'm using regex in Notepad ++.

I found this regex string to match everything after a certain comma to the end of the line:

,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*$

But how do I turn it around to start from the beginning?

I appreciate your time and help, thank you.

Upvotes: 3

Views: 1851

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

You may use

{(?:[^,}]*,){13}

Replace with a mere {. See the regex demo. This version will work correctly even if you have {...} substrings spanning across lines and having fewer than 13 items in between.

Details

  • { - a {
  • (?:[^,}]*,){13} - 13 consecutive occurrences of
    • [^,}]* - 0+ chars other than , and } (the } is important to avoid overflowing from one {...} substring into another)
    • , - a comma

You may also use

{\K(?:[^,}]*,){13}

And replace with an empty string. See another regex demo. You do not need to replace with { because \K omits the first { from the match, and it is thus kept in the final text.

enter image description here

Upvotes: 2

jaytea
jaytea

Reputation: 1949

Whereas $ matches the end of the subject string, ^ matches the beginning. So if you want to match up to and including the 13th comma:

^[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*, 

Replace with "{".

Upvotes: 2

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520878

Try the following find and replacement:

Find:

\{(?:[^,]*,){13}(.*)

Replace:

{$1

The above pattern could be slightly adjusted depending on what your expectations are for where this bracketed string might appear, edge cases you want to cover/avoid, etc.

Demo

Upvotes: 1

Related Questions