【问题标题】:NODEJS: extracting strings between two DIFFERENT characters and storing them in an arrayNODEJS:提取两个不同字符之间的字符串并将它们存储在数组中
【发布时间】:2017-01-13 20:57:44
【问题描述】:

使用 nodejs,我需要提取两个不同字符之间的所有字符串,并将它们存储在一个数组中以备将来使用。 例如,考虑一个文件,其中包含具有以下内容的文件。

"type":"multi",
"folders": [
    "cities/",
    "users/"
]

我需要提取单词:citiesusers,并将它们放在一个数组中。一般来说,我想要“和/”之间的单词

【问题讨论】:

  • 我对 nodejs 和 javascript 非常陌生。我将其用作练习。我发现这样做的方法是使用匹配方法。但我未能放置正确的分隔符
  • 您能否将您的失败尝试添加到问题中,以便我们有共同点来讨论
  • 您的文件实际上是否包含 JSON?还是那是 YAML?解析它。

标签: javascript arrays regex node.js string


【解决方案1】:

正如Bergi 在评论中提到的那样,这看起来与 JSON (javascript object notation.) 非常相似。所以我会假设它是这样写我的答案。为了使您当前的示例成为有效的 JSON,它需要位于对象括号内,如下所示:

{
    "type": "multi",
    "folders": [
        "cities/",
        "users/"
    ]
}

如果你解析这个:

var parsed_json = JSON.parse( json_string );

// You could add the brackets yourself if they are missing:
var parsed_json = JSON.parse('{' + json_string + '}');

那么你所要做的就是到达数组:

var arr = parsed_json.folders;
console.log(arr);

为了解决令人讨厌的尾部斜杠,我们重新映射数组:

// .map calls a function for every item in an array
// And whatever you choose to return becomes the new array
arr = arr.map(function(item){ 
  // substr returns a part of a string. Here from start (0) to end minus one (the slash).
  return item.substr( 0, item.length - 1 );

  // Another option could be to instead just replace all the slashes:
  return item.replace( '/' , '' );
}

现在尾部的斜线消失了:

console.log( arr );

【讨论】:

    【解决方案2】:

    这应该可行。

    "(.+?)\/"
    
    1. " 前面
    2. 1 个或多个字符(非贪婪)
    3. 后跟 /"

    REGEX101

    【讨论】:

    • 谢谢,这很有帮助。但是,这会提取 " 和 / 与字符串。但我不希望这些字符包含在子字符串中
    • 你想从那个 JSON 中得到什么输出?
    • 如果您将 REGEX 更改为 (?:")(.+?)(?:\/") ,则 " 等位于非捕获组中。如果这是您想要的。
    猜你喜欢
    • 2015-05-04
    • 1970-01-01
    • 1970-01-01
    • 2015-05-05
    • 1970-01-01
    • 1970-01-01
    • 2018-01-01
    • 1970-01-01
    • 2018-05-11
    相关资源
    最近更新 更多