简体   繁体   English

正则表达式用于转义特殊字符

[英]RegEx for escaping special characters

Trying RegExp to generate regular expression for string matching. 尝试RegExp生成用于字符串匹配的正则表达式。 Got confused with escaping specified in the docs . docs中指定的转义混淆了。 Whenever using RegExp constructor type input string need to escaped using function provided in that docs. 每当使用RegExp构造函数类型输入字符串时,都需要使用该文档中提供的函数进行转义。

Properly working with literal approach 正确使用文字方法

 "test".match(/te*/gi)

Output: 输出:

[ 'te', 't' ] ['te','t']

When I tried same thing with RegExp constructor output varies. 当我尝试使用RegExp构造函数进行相同操作时,输出会有所不同。

rg="te*"
function escapeRegExp(str) {
   return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

exp = new RegExp(escapeRegExp(rg),'gi')
console.log("exp =>", exp);
console.log("test".match(exp));

Output: 输出:

exp => /te*/gi exp => / te * / gi

null 空值

Will it be there any backslashes before '*'? '*'之前会有反斜杠吗? Is it properly escaped? 是否正确逃脱了? Why the regex generated is different from literal expression? 为什么生成的正则表达式与文字表达式不同? I couldn't figure out what I am missing from that doc. 我无法弄清楚该文档中缺少的内容。

I appreciate the help to point out mistake available here! 感谢您帮助指出此处的错误!

Because you don't want to escape the * - it's a regex character: 因为您不想转义* -这是一个正则表达式字符:

 const temp = "te*"; const reg = new RegExp(temp, "gi"); console.log("test".match(reg)); 

My doubt is [ \\ ^ $ . 我的疑问是[\\ ^ $。 | | ? * + ( ) all these need to be escaped before passing new RegExp() or only (backslashes \\) alone need to be escaped. * +()所有这些都需要在传递新的RegExp()之前进行转义,或者仅需单独转义(反斜杠\\) Which one need to be escaped or not be escaped is not clear to me? 我不清楚哪个需要逃避还是不逃避?

Your question is answered right at the start of the document section you refer to. 您所参考的文档部分的开头就回答了您的问题。 Read that again: 再读一遍:

If you need to use any of the special characters literally (actually searching for a '*', for instance), you must escape it … 如果您需要按字面使用任何特殊字符(例如,实际上是搜索“ *”),则必须对其进行转义...

Conversely, if you need any of the special characters to have its special meaning, you must not escape it. 相反,如果您需要任何特殊字符来具有其特殊含义,则不得转义它。

Besides the above, any backslash which is to be placed in the string has to be doubled if assigned from a string literal . 除上述内容外,如果从字符串常量分配,则要放在字符串中的任何反斜杠都必须加倍。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM