Skip to main content
devtools24

Regex 转义

转义特殊 regex 字符以字面匹配它们。也处理替换字符串的转义。

Text to Escape0 chars
Escaped for Regex Pattern
Escaped output...
Escaped for Replacement String
Escaped for replacement...

For replacement strings, only $ needs escaping (as $$)

.Any character
*0 or more
+1 or more
?0 or 1
^Start of string
$End of string
{Quantifier start
}Quantifier end
(Group start
)Group end
[Class start
]Class end
|Alternation
\Escape character

Regex Special Characters - 技术详情

Special regex characters like . * + ? ^ $ { } ( ) | [ ] \\ have special meanings. To match them literally, prefix with a backslash. For replacement strings, $ needs to be escaped as $$.

命令行替代方案

// JavaScript regex escape function
function escapeRegex(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

参考

查看官方规范