简体   繁体   中英

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.

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 "{".

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.

在此输入图像描述

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM