挑出每个数字并将其添加到数组中

时间:2016-07-26 22:24:23

标签: javascript arrays

所以我这里有一些文字

| | Serial: N/A | | UserID: 132382474 | |
| | Serial: N/A | | UserID: 132382474 | |
| | Serial: N/A | | UserID: 132382474 | |
| | Serial: N/A | | UserID: 131046468 | |

我想让它获取“UserID”之后的每个数字,并使用Javascript将其放入数组中 我怎么做这样的事情?

3 个答案:

答案 0 :(得分:0)

你所拥有的东西看起来有点像管道分隔的数据。不确定你到底在做什么,但我将假设以下事项:

  • 您有时会在| | s
  • 之间找到一些东西
  • 您希望所有数据都进入,而不仅仅是UserID s
  • 这不是节点流或其他一些流,而只是一个很大的文本。如果是的话,你必须在你去的时候逐行打破......

所以这里......

var someText = 
  "| | Serial: N/A | | UserID: 132382474 | |\n"
  +"| | Serial: N/A | | UserID: 132382474 | |\n"
  +"| | Serial: N/A | | UserID: 132382474 | |\n"
  +"| | Serial: N/A | | UserID: 131046468 | |";

var lines = someText.split('\n'); //Break apart by line
var data = lines.map(function(line) {
  var entries = line.split('|'); //Break apart by pipe
  var output = {};
  entries.forEach(function(entry) {
    var keyValue = entry.split(':'); //Break apart by colon
    if (!keyValue[1]) {
      return; //We don't have something in the form of 'key: value'
    }
    var key = keyValue[0].trim(); //This will get rid of unwanted whitespace
    var value = keyValue[1].trim();
    output[key] = value;
  });
  return output;
});

console.log(data);
希望有所帮助!

答案 1 :(得分:0)

你正在寻找一个全球匹配,使用它:

text.match(/\d+/g)

下式给出:

var text = "| | Serial: N/A | | UserID: 132382474 | |\
| | Serial: N/A | | UserID: 132382474 | |\
| | Serial: N/A | | UserID: 132382474 | |\
| | Serial: N/A | | UserID: 131046468 | |";

答案 2 :(得分:-1)

您可以使用String.prototype.match()提取这些数字,但是您必须使用g标记,因为您将提取多个数字,而String.prototype.match()会因全局搜索而失败(如果您'计划使用捕获)。您可以使用自定义匹配功能:

var text = "| | Serial: N/A | | UserID: 132382474 | |\
| | Serial: N/A | | UserID: 132382474 | |\
| | Serial: N/A | | UserID: 132382474 | |\
| | Serial: N/A | | UserID: 131046468 | |";

function match(string, regex) {
  var matches = [];
  var match = null;
  while (match = regex.exec(string)) {
    matches.push(match[1]);
  }
  return matches;
}

var numbers = match(text, /UserID:\s(\d*)?/g);

console.log(numbers);

正则表达式的解释:

            capture only the numbers -> 132382474
           /-\
/UserID:\s(\d*)?/g      g -> global search, search multiple times
\______________/
        |
search this pattern ->  UserID: 132382474

您必须使用g标记传递模式,否则while将创建无限循环。

或者只是使用其他功能确保模式具有g标志。这样,您可以传递没有g标志的模式。 global()函数将检查模式。如果它缺少g标志,它会自动添加。

var text = "| | Serial: N/A | | UserID: 132382474 | |\
| | Serial: N/A | | UserID: 132382474 | |\
| | Serial: N/A | | UserID: 132382474 | |\
| | Serial: N/A | | UserID: 131046468 | |";

function match(string, regex) {
  var regex	= global(regex);
  var matches	= [];
  var match	= null;
  while (match = regex.exec(string)) {
    matches.push(match[1]);
  }
  return matches;
}

function global(re) {
  var pattern	= re.source;
  var flags	= re.global ? re.flags : re.flags += "g";
  return new RegExp(pattern, flags);
}

var numbers = match(text, /UserID:\s(\d*)?/);

console.log(numbers);