简体   繁体   English

JavaScript:提取字符串中所有出现的正则表达式

[英]JavaScript: extract all occurrences of a regular expression in a string

I've got a Python function that makes a list of integer numbers out of a string containing clusters of digits: 我有一个Python函数,该函数从包含数字簇的字符串中组成一个整数列表:

def str_strip_numbers(s):
    """
    Returns a vector of integer numbers
    embedded in a string argument
    """
    return [int(x) for x in re.compile('\d+').findall(s)]

Given, say, an1kb12s336z , it returns [1,12,336] 假设有an1kb12s336z ,则返回[1,12,336]

What is the best way to get the same in JavaScript? 在JavaScript中获得相同效果的最佳方法是什么? I fiddled a bit with regular expressions, but did not gain much. 我用正则表达式摆弄了些花,但并没有收获多少。 This is not quite what I hoped for: 这不是我所希望的:

> var nn = /\d+/g
undefined
> nn
/\d+/g
> 'aba12gg4a'.search(nn)
3

Looks like I got the count of digits. 看起来我得到了数字计数。

Search is not the function you are looking for. 搜索不是您要查找的功能。 String.prototype.search() returns the position of the first matching result. String.prototype.search()返回第一个匹配结果的位置

You should instead use String.prototype.match: 'aba12gg4a'.match(/\\d+/g) . 您应该改用String.prototype.match: 'aba12gg4a'.match(/\\d+/g) This will return an array of all matches found in the source string. 这将返回在源字符串中找到的所有匹配项的数组。

you could try this. 你可以试试看 It will remove any letters from the string, and split to an array on the numbers. 它将删除字符串中的所有字母,并拆分为数字数组。 then filter out any values that don't parse with parseInt, meaning characters. 然后过滤掉任何不使用parseInt解析的值,即字符。

 'aba12gg4a'.split(/[^0-9]+/).reduce(function( ret, elem ){
        if (! isNaN(elem = parseInt(elem))){
            ret.push( elem );
        }
        return ret;
    }, []);
strStripNumbers: function(str) {
  return str.match(/\d+/g).map(__.parseInt);
}

__ means lodash library __表示lodash

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM