按空格拆分字符串,忽略转义的空格

Split string by whitespaces, ignoring escaped whitespaces

我一直在使用 Percentage Strings Literal"one two three four\ five" 之类的字符串转换为数组。

%w(one two three four\ five)

returns:

["one", "two", "three", "four five"]

现在我想动态地执行此操作,这样就可以再使用 Literals 了。

我可以使用哪种正则表达式模式将上面的字符串转换为数组?

我正在寻找一个正则表达式模式以放入 ruby 拆分方法中,该方法将采用 "one two three four\ five" 和 return ["one", "two", "three", "four five"]

注意:我只想按 未转义 的空格进行拆分,如上。四和五合并为同一个字符串,因为分隔它们的空格被转义了。

你可以试试这个:

(?<!\)\s+

Explanation

示例:

a='one two three four\ five';
b=a.split(/(?<!\)\s+/);
print(b);

Run here

如果您的字符串没有转义序列,您可以使用

的拆分方法
.split(/(?<!\)\s+/)

此处,(?<!\)\s+ 匹配前面没有 \.

的 1+ 个空格 (\s+)

如果您的字符串可能包含转义序列,匹配 方法更可取,因为它更可靠:

.scan(/(?:[^\\s]|\.)+/)

参见Ruby demo

它将匹配除 \ 和空格(使用 [^\\s])之外的 1 个或多个字符以及任何转义序列(使用 \. 匹配,一个反斜杠 + 除行以外的任何字符打断字符)。

要删除 \ 符号,您稍后必须使用 gsub

试试这个

require 'shellwords'

'one two three four\ five'.shellsplit
# => ["one", "two", "three", "four five"]

不需要正则表达式。