等价于Perl的\ Q ... \ E或quotemeta()的Javascript [英] Javascript equivalent of Perl's \Q ... \E or quotemeta()
问题描述
在Perl正则表达式中,您可以用\Q
和\E
包围子表达式,以表明您希望将该子表达式作为文字字符串进行匹配,即使其中存在元字符也是如此.您还具有quotemeta
函数,该函数可在字符串中插入正确数量的反斜杠,因此,如果随后将该字符串内插到正则表达式中,则无论其内容是什么,它都将按字面值进行匹配.
Javascript(在主要浏览器中部署的)是否具有等效的内置?我可以写我自己的东西,但是我想知道是否不必打扰.
没有此类内置功能.</p>
建议您不要研究自己的,而应该研究一下 regex转义功能.互联网.
该页面提出了以下解决方案(通过 Colin Snover ):
RegExp.escape = function(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
或建议使用 XRegExp 库.
In Perl regular expressions, you can surround a subexpression with \Q
and \E
to indicate that you want that subexpression to be matched as a literal string even if there are metacharacters in there. You also have the quotemeta
function that inserts exactly the right number of backslashes in a string so that if you subsequently interpolate that string into a regular expression, it will be matched literally, no matter what its contents were.
Does Javascript (as deployed in major browsers) have any built in equivalent? I can write my own just fine, but I would like to know if I don't have to bother.
There is no such built-in feature.
Rather than implementing your own, I advise you look into the multitude of regex escape functions available on the internet.
That page proposes the following solution (by Colin Snover):
RegExp.escape = function(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
or advises to use the XRegExp library.
这篇关于等价于Perl的\ Q ... \ E或quotemeta()的Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!