AlphaWolf
AlphaWolf

Reputation: 181

regex how to remove commas after a specific word

I am currently trying to remove any commas after the specific word 'SUM(' and Before the last ')' by using a regex. In other words, I want to remove all the beginning and end commas inside of the function SUM(). I am using the javascript function replace to do this on a regex.

Here are examples to illustrate what I am trying to do after the replace function is called with a regex:

SUM(,,,,1,2,)  // result should be SUM(1,2)
SUM(,1,2,)    // result should be SUM(1,2)
SUM(,1,2,,,)  // result should be SUM(1,2)
SUM(,,,,1,34) // result should be SUM(1,34)
SUM(,,,,0,0,0) // result should be SUM(0,0,0)

Currently I have been trying this regex:

(^SUM\()\,|(\,+)\)$

But I only want to match on the commas that are after the word 'SUM(' and Before the last bracket ')'. Please can someone help me.

Upvotes: 0

Views: 1305

Answers (2)

user663031
user663031

Reputation:

Replace multiple commas with one comma, then fix up the beginning and end:

str . 
  replace(/,+/g, ',') . 
  replace(/\(,/, '(') . 
  replace(/,\)/, ')')

If you don't care about removing multiple commas between items, then

str . replace(/\(,+/g, '(') . replace(/,+\(/, '(')

You could use combine these into a single regexp as

var str = "SUM(,1,2,,,)";
var result = str.replace(/(\(),+|,+(\))|(,),*/g, '$1$2$3')
//                        ^^^^^^               MATCH (,,,
//                               ^^^^^^        MATCH ,,,)
//                                      ^^^    MATCH commas between items
                             

document.write(result);

Upvotes: 0

Shafizadeh
Shafizadeh

Reputation: 10340

Use this pattern:

/(^SUM)\(,*(.*?),*\)/gm

And replace it with $1($2).

Online Demo

Upvotes: 2

Related Questions