E4218

E4218#

Compiler diagnostic name: lexscan_pattern_not_anchored.

词法正则模式没有在要求锚定的位置进行锚定。

lexscan 使用的模式(包括扫描内存中的 @lexbuf.StringScanner),以及采用 longest 策略的 lexmatch 模式,都必须从当前输入位置开始。请使用 ^ 锚定每个这样的正则。

错误示例#

///|
pub fn classify(input : String) -> String {
  lexmatch input with longest {
    re"[a-z]+" => "word"
    _ => "other"
  }
}

建议#

在正则开头添加 ^。只有当 case 必须消耗整个输入时,才还需要添加 $

///|
pub fn classify(input : String) -> String {
  lexmatch input with longest {
    (re"^[a-z]+", after=_) => "word"
    _ => "other"
  }
}