【问题标题】:Parse string to commandline-like array将字符串解析为类似命令行的数组
【发布时间】:2016-09-25 07:13:32
【问题描述】:

我正在使用 Node 制作一个交互式应用程序,它(显然)需要用户输入。我有这么多的工作,但有些输入有空格,.split(' ') 调用会混淆。

正在发生的事情的示例:

> foo "hello world" bar
['foo','"hello','world"','bar']

我想要发生的事情:

> foo "hello world" bar
['foo','hello world','bar']

我尝试过寻找 npm 包,但没有任何运气。

编辑:我知道我可以使用正则表达式,但我不知道正确的顺序是什么。

【问题讨论】:

    标签: javascript arrays node.js string


    【解决方案1】:

    如果你不想使用正则表达式,你可以这样做

    'foo "hello world" bar'.replace('"',"").split(" ");
    

    或确保包含单引号输入案例,您可以使用如下简单的正则表达式

    console.log('foo "hello world" bar'.replace(/("|')/g,"").split(" "));

    好吧,这是我对正则表达式的更正。这个只会捕获引号之间的文本,不包括引号而不使用任何捕获组。由于我们不使用任何捕获组,因此可以使用简单的String.prototype.match() 方法一次性解析我们想要的键数组,而无需循环。

    [^"]+(?="(\s|$))|\w+
    

    Debuggex Demo

    var reg = /[^"]+(?="(\s|$))|\w+/g,
        str = 'baz foo "hello world" bar whatever',
        arr = str.match(reg);
    console.log(arr);

    【讨论】:

    • 这正是我想要避免的输出
    • @Emilia 对不起,我的错。更正后的代码附在误导性代码下方。再次抱歉。
    【解决方案2】:

    您可以使用match()

    console.log(
      'foo "hello world" bar'.match(/"[^"]+"|\w+/g)
    )

    Regex explanation here


    如果您想避免使用",请使用捕获的组正则表达式和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);

    Regex explanation here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-06
      • 2023-03-21
      • 2019-09-04
      • 2020-11-11
      • 1970-01-01
      • 2016-07-30
      • 1970-01-01
      相关资源
      最近更新 更多