Capture all Regex matches into a vector

断了今生、忘了曾经 提交于 2021-02-16 16:19:26

问题


I'd like to capture all the numbers in a string and return a vector of integers, something like this (the result can be an empty vector):

fn str_strip_numbers(s: &str) -> Vec<isize> {
    unimplemented!()
}

A Python prototype:

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)]

For "alfa" the result is [], for "42by4" it is [42, 4].

What is the idiomatic way to get it in Rust?

UPD:

fn str_strip_numbers(s: &str) -> Vec<String> {
    lazy_static! {
        static ref RE: Regex = Regex::new(r"\d+").unwrap();
    }
    RE.captures(s).and_then(|cap| {cap})
}

I tried something like this, which is grossly wrong on more than one count. What would be the right approach?


回答1:


If you want all of the matches then you probably want to use find_iter(), which gives you an iterator over all of the matches. Then you'll need to convert the string matches into integers, and finally collect the results into a vector.

use lazy_static::lazy_static;
use regex::Regex;

fn str_strip_numbers(s: &str) -> Vec<i64> {
    lazy_static! {
        static ref RE: Regex = Regex::new(r"\d+").unwrap();
    }
    // iterate over all matches
    RE.find_iter(s)
        // try to parse the string matches as i64 (inferred from fn type signature)
        // and filter out the matches that can't be parsed (e.g. if there are too many digits to store in an i64).
        .filter_map(|digits| digits.as_str().parse().ok())
        // collect the results in to a Vec<i64> (inferred from fn type signature)
        .collect()
}


来源:https://stackoverflow.com/questions/58010114/capture-all-regex-matches-into-a-vector

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!