Home > Blockchain >  Regex to find the nth comma and remove the comma as well as the value
Regex to find the nth comma and remove the comma as well as the value

Time:12-09

Trying to remove the value after 3rd comma and the comma as well

a,b,c,d,e,f 
g,h,i,asj,k,l

How do write regex to find the 3 comma and remove ,d and ,asj ? I tried this /(?=(,[^,]{0,3}\n but not able to get it working

CodePudding user response:

You can use

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

Replace with $1 to restore the captured Group 1 value. See the regex demo.

Details:

  • ^ - start of string
  • ([^,]*(?:,[^,]*){2}) - Group 1:
  • [^,]* - zero or more chars other than a comma
  • (?:,[^,]*){2} - two occurrences of a comma and then zero or more chars other than a comma
  • , - a comma
  • [^,]* - zero or more chars other than a comma.
  • Related