Skip to main content

prefer-regexp-exec

Enforce RegExp#exec over String#match if no global flag is provided.

🔧

此规则报告的一些问题可通过 --fix ESLint 命令行选项自动修复

💭

该规则需要 类型信息 才能运行,但这会带来性能方面的权衡。

当正则表达式不包含 g 标志时,String#match 被定义为与 RegExp#exec 工作相同。坚持使用两者之一有助于提高代码的可读性。

¥String#match is defined to work the same as RegExp#exec when the regular expression does not include the g flag. Keeping to consistently using one of the two can help improve code readability.

此规则报告何时 String#match 操作组合了两个不同类型的值,或不是 RegExp#exec、 或 的类型。

¥This rule reports when a String#match call can be replaced with an equivalent RegExp#exec.

RegExp#exec 也可能比 String#match 稍快;这就是选择它作为首选用途的原因。

¥RegExp#exec may also be slightly faster than String#match; this is the reason to choose it as the preferred usage.

eslint.config.mjs
export default tseslint.config({
rules: {
"@typescript-eslint/prefer-regexp-exec": "error"
}
});

在线运行试试这个规则 ↗

示例

¥Examples

'something'.match(/thing/);

'some things are just things'.match(/thing/);

const text = 'something';
const search = /thing/;
text.match(search);
Open in Playground

选项

该规则不可配置。

何时不使用它

¥When Not To Use It

如果你希望在有和没有 g 标志的情况下一致使用 String#match,则可以关闭此规则。

¥If you prefer consistent use of String#match for both with g flag and without it, you can turn this rule off.


Type checked lint rules are more powerful than traditional lint rules, but also require configuring type checked linting.

See Troubleshooting > Linting with Type Information > Performance if you experience performance degradations after enabling type checked rules.

'## 资源'