You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用正则匹配引号外字符,正确提取含空格的引号内内容?

问题描述

我有一个包含如下自定义代码的文件:

#include "folder/file.txt"
#include "folder with spaces/file.txt"
#include "$variable/file.txt"
#define $foo joe
#define $bar 34

我希望通过JavaScript正则匹配提取每行的值。使用[^#"\s]+这类正则时,多数值匹配正确,但引号内的空格会被拆分,得到如下结果:

include
folder/file.txt
include
folder
with
spaces/file.txt
include
$variable/file.txt
define
$foo
joe
define
$bar
34

我需要忽略引号内的空格,得到如下匹配结果:

include
folder/file.txt
include
folder with spaces/file.txt
include
$variable/file.txt
define
$foo
joe
define
$bar
34

我尝试使用前瞻正则[^\s]+(?=(?:[^"]|["][^"]*["])*$),但该正则会忽略引号内空格前的内容,结果如下:

include
"folder/file.txt"
include
spaces/file.txt"
include
"$variable/file.txt"
define
$foo
joe
define
$bar
34

请问有什么更好的解决方法?

解决方案

可以使用一个能同时匹配引号内完整内容和非空格非引号片段的正则,具体如下:

/"[^"]+"|[^\s"]+/g

正则解释

  • "[^"]+":匹配被双引号包裹的内容,包括引号内的空格,直到闭合引号为止;
  • [^\s"]+:匹配不包含空格和双引号的连续字符,对应指令名(如include、define)、宏名、宏值这类无空格的片段;
  • g:全局匹配标志,确保提取所有符合条件的内容。

匹配结果

使用该正则后,会得到期望的输出:

include
folder/file.txt
include
folder with spaces/file.txt
include
$variable/file.txt
define
$foo
joe
define
$bar
34

扩展说明

如果你的场景中存在转义引号(如"folder\"name/file.txt"),需要调整正则为/"(?:\\.|[^"])+"|[^\s"]+/g,用来正确处理转义的引号字符。

内容的提问来源于stack exchange,提问作者Kim T

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 07:18:42