简体   繁体   English

正则表达式如何删除特定单词后的逗号

[英]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. 我目前正在尝试使用正则表达式删除特定单词'SUM(')和最后一个')'之后的逗号。 In other words, I want to remove all the beginning and end commas inside of the function SUM(). 换句话说,我想删除函数SUM()内的所有开头和结尾逗号。 I am using the javascript function replace to do this on a regex. 我正在使用javascript函数replace在正则表达式上执行此操作。

Here are examples to illustrate what I am trying to do after the replace function is called with a regex: 以下示例说明了使用正则表达式调用replace函数后我要执行的操作:

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 ')'. 但是我只想匹配单词'SUM(')和最后一个括号')'之前的逗号。 Please can someone help me. 请有人帮我。

Use this pattern: 使用以下模式:

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

And replace it with $1($2) . 并替换为$1($2)

Online Demo 在线演示

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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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