我目前有这个正则表达式来按所有空格分割字符串,除非它在引用的段中:
keywords = 'pop rock "hard rock"';
keywords = keywords.match(/\w+|"[^"]+"/g);
console.log(keywords); // [pop, rock, "hard rock"]
Run Code Online (Sandbox Code Playgroud)
但是,我也希望可以在关键字中使用引号,如下所示:
keywords = 'pop rock "hard rock" "\"dream\" pop"';
Run Code Online (Sandbox Code Playgroud)
这应该回来了
[pop, rock, "hard rock", "\"dream\" pop"]
Run Code Online (Sandbox Code Playgroud)
实现这一目标的最简单方法是什么?
使用Fuse.js我试图在 JS 对象中进行“多词”搜索,以获取包含所查找的每个词的记录。
我的数据结构如下(来自fuse.js):
[{
title: "The Lost Symbol",
author: {
firstName: "Dan",
lastName: "Brown"
}
}, ...]
Run Code Online (Sandbox Code Playgroud)
我的问题是我的设置适用于单字搜索(Brown例如),但不适用于更多(Dan Brown或Dan Brown Vinci)。
保险丝选项:
{
shouldSort: true,
matchAllTokens: true,
findAllMatches: true,
includeScore: true,
threshold: 0,
location: 0,
distance: 100,
maxPatternLength: 32,
minMatchCharLength: 1,
keys: [
"title",
"author.firstName",
"author.lastName"
]
}
Run Code Online (Sandbox Code Playgroud)
[{
title: "The Lost Symbol",
author: {
firstName: "Dan",
lastName: "Brown"
}
}, ...]
Run Code Online (Sandbox Code Playgroud)
{
shouldSort: true,
matchAllTokens: true,
findAllMatches: true, …Run Code Online (Sandbox Code Playgroud)最终我试图改变这个:
var msg = '-m "this is a message" --echo "another message" test arg';
Run Code Online (Sandbox Code Playgroud)
进入这个:
[
'-m',
'this is a message',
'--echo',
'another message',
'test',
'arg'
]
Run Code Online (Sandbox Code Playgroud)
我不太确定如何解析字符串以获得所需的结果.这是我到目前为止:
var msg = '-m "this is a message" --echo "another message" test arg';
// remove spaces from all quoted strings.
msg = msg.replace(/"[^"]*"/g, function (match) {
return match.replace(/ /g, '{space}');
});
// Now turn it into an array.
var msgArray = msg.split(' ').forEach(function (item) {
item = item.replace('{space}', ' ');
});
Run Code Online (Sandbox Code Playgroud)
我认为这样可行,但是人类看起来像是一种变幻无常的向后完成我想要的方式.我相信你们比分割前创建一个占位符字符串要好得多.
目标是在空格处拆分字符串,但不拆分引号中的文本数据或将其与相邻文本分开.
输入实际上是一个包含值对列表的字符串.如果值值包含空格,则用引号括起来.我需要一个函数,它返回一个值对元素数组,如下例所示:
示例输入:
'a:0 b:1 moo:"foo bar"c:2'
预期结果:
a:0,b:1,moo:foo bar,c:2(长度为4的数组)
我已经检查过其他一些问题,但没有一个(我发现)似乎能解决我的问题.大多数似乎在引号内的空格处分开,或者将"moo:"和"foo bar"分成不同的部分.
克雷格,非常感谢任何帮助