正则表达式选择引号中的所有空格?

Kln*_*h13 6 javascript regex textmate

例如:

string text = 'some text "and some more" and some other "this is a second group" okay the end';.

我想捕获引号之间的所有空格。最终目标是用逗号替换这些空格。

最终目标,例如:

'some text "and,some,more" and some other "this,is,a,second,group" okay the end'
Run Code Online (Sandbox Code Playgroud)

例如,这将在 javascript 中执行我想要的操作:

text.replace(/(["]).*?\1/gm, function ($0) {
    return $0.replace(/\s/g, ',');
});
Run Code Online (Sandbox Code Playgroud)

不幸的是,我唯一可用的工具是 textmate 的查找/替换功能。

我发现另一个与我需要的相反,但使用了我需要的一行:

text.replace(/\s+(?=([^"]*"[^"]*")*[^"]*$)/gm, ',');
Run Code Online (Sandbox Code Playgroud)

谢谢!

Wik*_*żew 6

您可以使用

\s+(?=(?:(?:[^"]*"){2})*[^"]*"[^"]*$)
Run Code Online (Sandbox Code Playgroud)

查看正则表达式演示

\s+匹配1个或多个空白后跟奇数双引号。

详细信息:空白匹配部分很简单,正向前瞻需要

  • (?:(?:[^"]*"){2})*- 零个或多个 2 个序列的序列匹配 0+ 个字符,而不是 a"和 a "(0+ "..."s)
  • [^"]*"[^"]*- 除 a 以外的 0+ 个字符"后跟 a"并再次跟随着除 a 以外的 0+ 个字符"(奇数引号必须在当前匹配的空格的右侧)
  • $ - 字符串的结尾。