首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >遍历正则表达式捕获的生存期问题

遍历正则表达式捕获的生存期问题
EN

Stack Overflow用户
提问于 2018-08-14 05:12:28
回答 1查看 434关注 0票数 1

我正在尝试使用regex从字符串中获取所有非空格字符,但我总是回到相同的错误。

代码语言:javascript
运行
复制
extern crate regex; // 1.0.2

use regex::Regex;
use std::vec::Vec;

pub fn string_split<'a>(s: &'a String) -> Vec<&'a str> {
    let mut returnVec = Vec::new();
    let re = Regex::new(r"\S+").unwrap();

    for cap in re.captures_iter(s) {
        returnVec.push(&cap[0]);
    }

    returnVec
}

pub fn word_n(s: &String, n: i32) -> &str {
    let bytes = s.as_bytes();

    let mut num = 0;
    let mut word_start = 0;
    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' || item == b'\n' {
            num += 1;
            if num == n {
                return &s[word_start..i].trim();
            }
            word_start = i;
            continue;
        }
    }

    &s[..]
}

错误:

代码语言:javascript
运行
复制
error[E0597]: `cap` does not live long enough
  --> src/main.rs:11:25
   |
11 |         returnVec.push(&cap[0]);
   |                         ^^^ borrowed value does not live long enough
12 |     }
   |     - borrowed value only lives until here
   |
note: borrowed value must be valid for the lifetime 'a as defined on the function body at 6:1...
  --> src/main.rs:6:1
   |
6  | pub fn string_split<'a>(s: &'a String) -> Vec<&'a str> {
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

再加上更多信息:

代码语言:javascript
运行
复制
$ rustc --explain E0597

This error occurs because a borrow was made inside a variable which has a
greater lifetime than the borrowed one.

Example of erroneous code:

结构Foo<'a> {

代码语言:javascript
运行
复制
x: Option<&'a u32>,

}

设mut x= Foo { x: None };

设y= 0;

x.x =一些(&y);//错误:y活得不够长

代码语言:javascript
运行
复制
In here, `x` is created before `y` and therefore has a greater lifetime. Always
keep in mind that values in a scope are dropped in the opposite order they are
created. So to fix the previous example, just make the `y` lifetime greater than
the `x`'s one:

结构Foo<'a> {

代码语言:javascript
运行
复制
x: Option<&'a u32>,

}

设y= 0;

设mut x= Foo { x: None };

x.x =一些(&y);

代码语言:javascript
运行
复制

此时,我尝试了几种方法来扩展cap变量的生存期,但是在阅读了Rust这本书的“借用和生命周期”部分之后,我无法得到任何有用的东西。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-14 07:30:21

impl<'t> Index for Captures<'t> (这是代码中的cap[0] )说:

如果使用此方法,文本不能超过捕获对象,因为索引是如何定义的(通常ai是a的一部分,不能超过它);要做到这一点,请使用get()。

因此,对于get,它可以工作(请注意,我已经用&'a str替换了&'a String参数):

代码语言:javascript
运行
复制
use regex::Regex;

pub fn string_split<'a>(s: &'a str) -> Vec<&'a str> {
    let mut return_vec = Vec::new();
    let re = Regex::new(r"\S+").unwrap();

    for cap in re.captures_iter(s) {
        return_vec.push(cap.get(0).unwrap().as_str());
    };

    return_vec
}

fn main() {
    println!("{:?}", string_split("Hello, world!"));
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51834111

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档