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

V 0.4.0正则匹配异常咨询:预期匹配'the'却无结果

问题原因及解决办法

你的代码问题出在使用了错误的正则匹配方法:

  • matches_string 用于判断整个字符串是否完全等于正则表达式匹配的内容,而非查找字符串中的子串
  • match_string 默认从字符串开头尝试匹配整个字符串,同样不是子串查找方法

所以你的正则the只能匹配完全是the的字符串,自然无法匹配长句子里的子串。

修正后的代码

使用find或find_all方法来查找字符串中的子串匹配:

import regex

fn main() {
	txt := 'Now is the time for all good men'
	query := r'the'
	mut re := regex.regex_opt(query) or { panic(err) }
	println(re.get_query())           //-> the

	// 查找第一个匹配的子串
	start_idx := re.find(txt)
	if start_idx >= 0 {
		start, end := re.match_string(txt, start_idx)
		println('Match: ${txt[start..end]} between ${start} and ${end}')
	} else {
		println('No match')
	}

	// 或者一次性获取所有匹配结果(更直观)
	all_matches := re.find_all(txt)
	for match_range in all_matches {
		println('Match: ${txt[match_range.start..match_range.end]} between ${match_range.start} and ${match_range.end}')
	}
}

关键方法说明

  • find(s string):返回第一个匹配子串的起始索引,无匹配则返回-1
  • find_all(s string):返回所有匹配子串的{start: int, end: int}数组
  • match_string(s string, pos int):从指定位置pos开始尝试匹配,返回匹配的起止索引

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 02:15:01