当 String.endsWith 接受 String 时,为什么 String.startsWith 将 Pattern 作为输入

Lub*_*rek 4 dart

两种执行非常相似的方法之间存在这种接口不匹配。

bool endsWith(String other)
bool startsWith(Pattern pattern, [int index=0])
Run Code Online (Sandbox Code Playgroud)

这是什么原因?作者的想法是什么?

Flo*_*sch 5

的 APIPattern不提供任何向后搜索匹配项的方法。如果endsWith采用一种模式,则需要逐一尝试从字符串的后面找到匹配项(这很可能在 O(n^2) 中)。

请注意,您不能只使用Pattern.allMatches并查看最后一个匹配是否在输入结束时结束:

var re = new RegExp('a|ab');
re.allMatches('ab'); // => one match: 'a'.
Run Code Online (Sandbox Code Playgroud)

在这个例子中,只有 'a' 匹配,如果我们使用allMatches迭代器来确定字符串是否以给定的正则表达式结尾,它将错误地失败。