在 RegExp 构建之前清理正则表达式字符串?

发布于 2024-11-14 22:07:20 字数 225 浏览 7 评论 0原文

我想使用一个字符串来执行全局正则表达式,但它可能包含正则表达式字符。在使用字符串构建正则表达式之前,转义字符串中所有正则表达式字符的最佳方法是什么?

基本上我可能有这样的东西;

var test = 'test.';
var regex = new RegExp(test, 'ig');

我需要“测试”。成为“测试”。所以它不会以意想不到的方式表现。

I want to use a string to perform a global regex, but it might have regex characters in it. What's the best way to escape all regex characters in a string before building a regex with it?

Basically I might have something like this;

var test = 'test.';
var regex = new RegExp(test, 'ig');

I need 'test.' to become 'test\.' so it doesn't behave in unexpected ways.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

木落 2024-11-21 22:07:20
new RegExp(test.replace(/[#-.]|[[-^]|[?|{}]/g, '\\
amp;'));

这会转义以下内容:

  • #. 之间的字符,因此: #$%&'()*+,-.
  • 这四个字符字符 [\]^
  • 这些字符 ?|, {, }

...by在每次出现之前添加反斜杠(如 $& 插入匹配的子字符串g标志表示替换所有实例。)


或者,如果您正在寻找较短的版本,请尝试:

new RegExp(test.replace(/[#-}]/g, '\\
amp;'));

这最终会转义比应有的更多的内容,但不会造成任何损害。

new RegExp(test.replace(/[#-.]|[[-^]|[?|{}]/g, '\\
amp;'));

This escapes the following:

  • The characters between # and ., so: #$%&'()*+,-.
  • The four characters [, \, ], and ^
  • These characters ?, |, {, }

...by prepending a backslash before each occurrence (as $& Inserts the matched substring, and the g flag means to replace all instances.)


Alternatively, if you're looking for a shorter version, try:

new RegExp(test.replace(/[#-}]/g, '\\
amp;'));

This will end up escaping a lot more than it should, but it won't harm anything.

揽月 2024-11-21 22:07:20

这将用转义版本替换所有特殊 RegExp 字符:

test = test.replace(/[\\\.\+\*\?\^\$\[\]\(\)\{\}\/\'\#\:\!\=\|]/ig, "\\
amp;");

This will replace all special RegExp characters with their escaped version:

test = test.replace(/[\\\.\+\*\?\^\$\[\]\(\)\{\}\/\'\#\:\!\=\|]/ig, "\\
amp;");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文