You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust使用regex库end方法报错E0599,求技术解决方案

Rust中使用regex的end方法报错解决

问题描述

我在尝试使用end方法查找字符串位置时遇到错误,以下是我的Rust代码:

extern crate regex;

use regex::Regex;

fn main() {
    /* Input for testing*/
    let text = "definitions:\n\ta = point(3,3); \n\td = point(9,4);\n\tx = circle(a,1);\n\ty = square(d,2)\n
operations:\n\tprint(x);\n\tprint(y);\n\tintercts(x,y)\nend.";

  let def_regex = Regex::new(r"^definitions").unwrap();
  let ws_regex = Regex::new(r"^ ").unwrap();

    while data.chars().count() > 0 {
        if ws_regex.is_match(&data)  {
            data = data.chars().skip(1).collect();
            continue;
        }
        if def_regex.is_match(&data) {
            let pos = def_regex.find(&data).unwrap();
            data = data.chars().skip(pos.end()).collect();
            println!("DEFINITIONS");
            continue;
        }
}
}

错误信息:

error[E0599]: no method named end found for tuple (usize, usize) in the current scope

我是Rust新手,搞不定这个问题,请求帮助。

解决方案

这个错误根源是你用的regex crate版本过旧:旧版本里find方法返回的是(usize, usize)元组,没有end()方法;而新版本返回的是Match结构体,才带有end()方法。

有两种解决方式:

  • 升级regex版本
    打开Cargo.toml,把regex依赖更新到最新稳定版,比如:

    [dependencies]
    regex = "1.10"
    

    升级后,原代码里的pos.end()就能正常工作,它会返回匹配字符串的结束索引。

  • 直接使用元组元素
    要是不想升级,直接用元组的第二个值代替end(),修改代码中的这一行:

    data = data.chars().skip(pos.1).collect();
    

    旧版本返回的元组中,第一个元素是匹配起始索引,第二个就是结束索引。

另外注意代码里的小问题:data变量未初始化,要把let text改成let mut data,因为后续需要修改它的值。

内容的提问来源于stack exchange,提问作者toughmuffin12

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 12:35:19