Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何捕获所有组并用组的重新格式化版本替换它们?_Javascript_Regex_Regex Group - Fatal编程技术网

Javascript 如何捕获所有组并用组的重新格式化版本替换它们?

Javascript 如何捕获所有组并用组的重新格式化版本替换它们?,javascript,regex,regex-group,Javascript,Regex,Regex Group,文本输入: some "single , quote" , text ""{one,2two space,three-dash,four}"" "{some,text}" ""{alpha,bravo space - dash,charlie}"" some text some "single , quote" , text ""{o

文本输入:

some "single , quote" , text ""{one,2two space,three-dash,four}"" "{some,text}"  ""{alpha,bravo space - dash,charlie}"" some text
some "single , quote" , text ""{one","2two space","three-dash","four}"" "{some,text}"  ""{alpha","bravo space - dash","charlie}"" some text
文本输出:

some "single , quote" , text ""{one,2two space,three-dash,four}"" "{some,text}"  ""{alpha,bravo space - dash,charlie}"" some text
some "single , quote" , text ""{one","2two space","three-dash","four}"" "{some,text}"  ""{alpha","bravo space - dash","charlie}"" some text
下面我有一个javascript解决方案可以使用,但我想知道是否有更好的解决方案


您可以为
replace()
方法提供一个函数作为替换参数,因此不需要循环

此外,还可以简化regexp。您不需要捕获组,只需将
*
量词放在
[^”]

const str='some,text”“{1,2个空格,3个破折号,4}”“some,text”“{alpha,bravo space-dash,charlie}”“some text';
res=str.replace(/“{[^”]*}”“/g,match=>match.replace(/,/g,“,”))

控制台日志(res)
您可以使用以下正则表达式匹配要替换为(三个字符串)
“,”
的逗号

匹配和替换结果将显示在字符串中

some, text ""{one,2two space,three-dash,four}"" some, text ""{alpha,bravo space - dash,charlie}"" some text';
some, text ""{one","2two space","three-dash","four}"" some, text ""{alpha","bravo space - dash","charlie}"" some text';
Javascript的正则表达式引擎执行以下操作

(?<=        : begin a positive lookbehind
  ""{       : match '""{'
  [^{}\n]*  : match 0+ chars other than those shown in the char class
)           : end positive lookbehind
,           : match ','
(?=         : begin positive lookahead
  [^{}\n]*  : match 0+ chars other than those shown in the char class
  }""       : match '}""'
)           : end positive lookahead

(?有用提示:如果您的字符串包含双引号,请在其周围使用单引号,这样您就不需要转义引号。此解决方案很棒!很好,感谢您的详细解释!