NODEJS:提取两个不同字符之间的字符串并将其存储在数组中

NODEJS: extracting strings between two DIFFERENT characters and storing them in an array

本文关键字:字符 串并 字符串 存储 数组 之间 NODEJS 提取 两个      更新时间:2023-09-26

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

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

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

正如Bergi在评论中提到的,这看起来与JSON (javascript对象表示法)非常相似。所以我就假设它是。为了使当前的示例是有效的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 );

应该可以。

"(.+?)'/"
    先前
  1. "
  2. 1个或多个字符(非贪婪)
  3. 后接/"

REGEX101