使用javascript从原始字符串中提取数字模式

时间:2017-08-18 10:20:22

标签: javascript

目前我有一个字符串 例如:

--3c8a15bdc66e76b5 Content-Type: text/plain X-Primitive: integer 8487823278258687528 --3c8a15bdc66e76b5-- 
--3c8a15bdc66e76b5 Content-Type: text/plain X-Primitive: integer 14918370877051183774 --3c8a15bdc66e76b5--

从上面的字符串我想提取:

8487823278258687528,14918370877051183774喜欢来自此原始字符串的数字字符串,并希望使用javascript保存在数组中。

请帮助。这将是很大的帮助。因为我是编程新手

2 个答案:

答案 0 :(得分:1)

你想要这样的东西



\b\d+\b




这将使用正则表达式匹配所有数字

{{1}}

这里\ b定义边界\ d +匹配所有数字,其中至少有1个数字

答案 1 :(得分:1)

您可以使用RegExp来完成此操作,然后将响应解析为整数。



const NUMBER_EXP = /( [0-9]+ )/g; // spaces to distinguish the number

let stringToParse = ' --3c8a15bdc66e76b5 Content-Type: text/plain X-Primitive: integer 8487823278258687528 --3c8a15bdc66e76b5-- --3c8a15bdc66e76b5 Content-Type: text/plain X-Primitive: integer 14918370877051183774 --3c8a15bdc66e76b5-- .';

let results = stringToParse
  .match(NUMBER_EXP)
  .map((value) => parseInt(value.trim(), 10));

console.log(results.join(', '));