解析字符串命令行状阵列 [英] Parse string to commandline-like array
本文介绍了解析字符串命令行状阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在与节点的互动应用程序,(显然)需要用户输入。我有那么多的工作,但一些输入有空格,其中 .split('')
调用会乱用。
发生了什么事的例子:
>富世界你好吧
['富','你好,世界的','酒吧']
我想会发生什么:
>富世界你好吧
['富','你好世界','酒吧']
我试图寻找一个NPM包,但没有任何运气。
修改:我知道我可以使用正则表达式,但我不知道正确的顺序应该为
解决方案
您可以使用的 匹配()
\r
\r\r
\r 的console.log(\r
富Hello World的bar'.match(/[^] +| \\ W + / G)\r
)
\r
如果你想避免然后使用捕获组的正则表达式是的
执行exec()
\r
\r\r
\r 无功海峡='富的Hello World酒吧;\r
VAR章= /([^] +)| \\ W + /克,\r
男,解析度= [];\r
\r
而(M = reg.exec(STR))\r
res.push(M [1] || M [0])\r
\r
的console.log(RES);
\r
I'm making an interactive app with Node that (obviously) takes user input. I have that much working, but some of the input has spaces, which a .split(' ')
call would mess with.
Example of what's happening:
> foo "hello world" bar
['foo','"hello','world"','bar']
What I want to happen:
> foo "hello world" bar
['foo','hello world','bar']
I've tried looking for an npm package, but haven't had any luck.
Edit: I'm aware I can use regex, but I have no idea what the proper sequence would be.
解决方案
You can use match()
console.log(
'foo "hello world" bar'.match(/"[^"]+"|\w+/g)
)
If you want to avoid "
then use captured group regex with exec()
var str = 'foo "hello world" bar';
var reg = /"([^"]+)"|\w+/g,
m, res = [];
while (m = reg.exec(str))
res.push(m[1] || m[0])
console.log(res);
这篇关于解析字符串命令行状阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文