我想捕获一个字符串中的所有数字并返回一个整数向量,如下所示(结果可以是一个空向量):
fn str_strip_numbers(s: &str) -> Vec<isize> {
unimplemented!()
}
Run Code Online (Sandbox Code Playgroud)
一个 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)]
Run Code Online (Sandbox Code Playgroud)
因为"alfa"结果是[],因为"42by4"它是[42, 4]。
在 Rust 中获得它的惯用方法是什么?
更新:
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})
}
Run Code Online (Sandbox Code Playgroud)
我试过这样的事情,这在不止一个计数上是严重错误的。什么是正确的方法?
如果您想要所有匹配项,那么您可能想要使用find_iter(),它为您提供所有匹配项的迭代器。然后您需要将匹配的字符串转换为整数,最后将结果收集到一个向量中。
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()
}
Run Code Online (Sandbox Code Playgroud)